title: What is the setlocal / endlocal equivalent for PowerShell?
body: <p><strong>Objective</strong></p>
  
  <p>Isolate <em>environmental variable</em> changes to a code block.</p>
  
  <p><strong>Background</strong></p>
  
  <p>If I want to create a batch script to run a command that requires an environmental variable set, I know I can do this:</p>
  
  <pre><code>setlocal
  set MYLANG=EN
  my-cmd dostuff -o out.csv
  endlocal
  </code></pre>
  
  <p>However, I tend to use PowerShell when I need to using a shell scripting language. I know how to set the environmental variable (<code>$env:TEST="EN"</code>) and of course this is just a simple example. However, I am not sure how to achieve the same effect that I could with a batch script. Surprisingly, I don't see any questions asking this either.</p>
  
  <p>I am aware that setting something with <code>$env:TEST="EN"</code> is process scoped, but that isn't practical if I'm using scripts as small utilities in a single terminal session. </p>
  
  <p><strong>My current approaches:</strong></p>
  
  <ol>
  <li>Entered <code>setlocal</code>. But that wasn't a commandlet... I hoped.</li>
  <li>Save the current variable to a temp variable, run my command, change it back... kinda silly.</li>
  <li>Function level scope (though I doubted the success since <code>$env:</code> seems to be not much unlike <code>$global:</code>)</li>
  </ol>
  
  <p>Function scope doesn't trump the reference to <code>$env:</code></p>
  
  <pre><code>$env:TEST="EN"
  function tt {
    $env:TEST="GB"
    ($env:TEST)
  }
  
  ($env:TEST)
  tt
  ($env:TEST)
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>C:\Users\me&gt; .\eg.ps1
  EN
  GB
  GB
  </code></pre>