title: How to make several commands run in their own scope in PowerShell, idiomatically?
body: <p>Let's say I'm doing some basic string manipulation, as follows:</p>
  <pre><code>$segments = $PathToExe -split &quot;\\&quot;
  $last = $segments[$segments.Length - 1]
  $ProcName = ($last -split &quot;\.&quot;)[0]
  </code></pre>
  <p>The purpose of this little piece of code is to get the &quot;name&quot; part of a path to an executable file, to later pass it to the <code>-Name</code> parameter of <code>Get-Process</code>.</p>
  <p>Writing this sequence of commands verbatim inside a script is simple enough, but it makes the temporary variables <code>$segments</code> and <code>$last</code> leak into the scope of the script. This may lead to unexpected results when similar variable names are introduced later, or, much worse and much more likely, miscommunicated intent of the variables. Clearly, semantically and functionally confining those variables to the specific task they're performing would improve maintainability of the script.</p>
  <p>There are different ways to implement this kind of behavior:</p>
  <ul>
  <li><strong>Wrap the code into  a function</strong>:
  <pre><code>function NameFromExePath([string] $Path)
  {
      $segments = $Path -split &quot;\\&quot;
      $last = $segments[$segments.Length - 1]
      return ($last -split &quot;\.&quot;)[0]
  }
  </code></pre>
  This is a bit bulky, worsening readability if you do it too often, in the common case where the function code is used only once in the script, right after the function itself.</li>
  <li><strong>Use a script block:</strong>
  <pre><code>$Name = icm {
      $segments = $PathToExe -split &quot;\\&quot;
      $last = $segments[$segments.Length - 1]
      return ($last -split &quot;\.&quot;)[0]
  }
  </code></pre>
  This incurs some overhead from <code>icm</code> and feels a bit like a hack. The role of <code>icm</code> is quite different from what it normally is.</li>
  <li><strong>Delete the variables:</strong>
  <pre><code># Piece of code from beginning of the question goes here
  # &lt;...&gt;
  rv segments
  rv last
  </code></pre>
  This is quite bulky, size scales linearly with the number of variables to remove, and is manual (and so error-prone).</li>
  </ul>
  <p>Out of those three approaches (and, hopefully, a much better one I don't know of), which one is the most idiomatic? Or is avoiding variable pollution like this not common practice to begin with?</p>