title: [Environment]::Exit(0) required, but how can I use a script with Invoke-Expression with that?
body: <p>It seems that I am in the powers<code>hell</code> with exit codes.</p>
  
  <p>There are many topics about why powershell behaves weird with its exit codes (for syntax errors, etc).
  There is furthermore a big issue with exit codes and the <code>Parameter</code> attribute. e.g.
  calling a script with the following code</p>
  
  <pre><code>Param(
    [Parameter()]$a
  )
  exit 9999
  </code></pre>
  
  <p>returns an exit code of <strong>0</strong> in cmd.exe (e.g. <code>echo %ERRORLEVEL%</code>) making it impossible to properly deal with return codes.</p>
  
  <p>The very last workaround for that is using Environment::Exit:</p>
  
  <pre><code>Param(
    [Parameter()]$a
  )
  [Environment]::Exit(9999)
  </code></pre>
  
  <hr>
  
  <p>Now the problem: I've written a script that has extensive <code>Param</code> definitions and therefore needs <code>Environment::Exit</code> to work.
  This utility returns a value via echo, here is a working script for that</p>
  
  <pre><code># dummy.ps1
  Param(
    [Parameter()]$a
  )
  
  echo "foo 42"
  
  [Environment]::Exit(10)
  </code></pre>
  
  <p>Of course I don't need the exit here, but the real-world script requires this to properly exit after the <code>echo</code> indicating exit code <strong>10</strong> in both <code>ps</code> and in <code>cmd</code></p>
  
  <p>Calling it via <code>powershell -f dummy.ps1</code> returns 42, everything is fine.</p>
  
  <p>But here is the problem: I want to reuse this script in another script so I can use the echoed value properly.</p>
  
  <p>When I am in the powershell prompt I want to do something like that:</p>
  
  <pre><code>$res = Invoke-Expression "&amp; d:\dummy.ps1"
  echo $res
  </code></pre>
  
  <p>But Environment::Exit closes my prompt after the Invoke-Expression and everything is gone.
  (Even if I put this code in a separate <code>ps1</code> file)</p>
  
  <p>Is there a scenario in which this entire thing works as expected?
  Again: I need proper exit codes for <code>ps</code> and <code>cmd</code> so <code>exit 10</code> or <code>exit(10)</code> fail here. And due to the behaviour with <code>[Parameter()]</code> no other exit code than Environment::Exit does work.</p>