title: Explain scoping for functions called from PowerShell closures
body: <p>The following PowerShell code displays unexpected scoping behavior for functions called from closures.  Can you explain whether this is "by design", or is a defect?</p>
  
  <pre><code>function runblock($block) {
      $x = 4
      &amp; $block
  }
  
  function printx() {
      "  in printx: x=" + $x
  }
  
  "PSVersion $($PSVersionTable.PSVersion)"
  
  $x = 1
  $b = {"In block x=" + $x ; $x = 3 ; printx}
  $x = 2
  runblock $b
  
  $x = 1
  $b = {"In closure x=" + $x ; $x = 3 ; printx}.GetNewClosure()
  $x = 2
  runblock $b
  </code></pre>
  
  <p>Output from the above is
  </p>
  
  <pre class="lang-none prettyprint-override"><code>PSVersion 3.0
  In block x=4
    in printx: x=3
  In closure x=1
    in printx: x=4
  </code></pre>
  
  <p>Most of the output makes sense to me:</p>
  
  <p>The script block outputs <code>In block x=4</code> since its parent scope is the <code>runblock</code> function. The <code>printx</code> function outputs <code>x=3</code> since its parent scope is the script block scope.</p>
  
  <p>The closure outputs <code>In closure x=1</code> since the value of <code>$x</code> was captured by <code>GetNewClosure</code> call.  All as expected.</p>
  
  <p>BUT:
  The call to <code>printx</code> from the closure outputs <code>in printx: x=4</code>.  So the scope that <code>printx</code> executes within is unaffected by the scope of the closure where <code>$x = 3</code>.</p>
  
  <p>It seems strange to me that a function called from a normal script block does see the variables in the script block scope, but a function called from a closure does not see the variables in the closure.</p>