title: How to prevent exit of host and return exit code?
body: <p>Ansgar Wiechers' answer works well whenever starting a new PowerShell process. <a href="https://stackoverflow.com/a/50202663/447901">https://stackoverflow.com/a/50202663/447901</a> This works in both cmd.exe and powershell.exe.</p>
  
  <pre><code>C:&gt;type .\exit1.ps1
  function ExitWithCode($exitcode) {
    $host.SetShouldExit($exitcode)
    exit $exitcode
  }
  ExitWithCode 23
  </code></pre>
  
  <p>In a cmd.exe interactive shell.</p>
  
  <pre><code>C:&gt;powershell -NoProfile -Command .\exit1.ps1
  C:&gt;echo %ERRORLEVEL%
  23
  C:&gt;powershell -NoProfile -File .\exit1.ps1
  C:&gt;echo %ERRORLEVEL%
  23
  </code></pre>
  
  <p>In a PowerShell interactive shell.</p>
  
  <pre><code>PS C:&gt;powershell -NoProfile -Command .\exit1.ps1
  PS C:&gt;$LASTEXITCODE
  23
  PS C:&gt;powershell -NoProfile -File .\exit1.ps1
  PS C:&gt;$LASTEXITCODE
  23
  </code></pre>
  
  <p>HOWEVER... Running the .ps1 script inside an existing interactive PowerShell host will exit the host completely.</p>
  
  <pre><code>PS C:&gt;.\exit1.ps1
      &lt;&lt;&lt;poof! gone! outahere!&gt;&gt;&gt;
  </code></pre>
  
  <p>How can I prevent it from exiting the host shell?</p>