title: Return values of spawned powershell.exe and cmd.exe shells
body: <p>The background here is that I'm using SaltStack on Windows, and because it's Windows support is patchy I have to get it to run a lot of batch and powershell scripts or commands.</p>
  
  <p>Salt is a Python program, so it spawns instances of powershell.exe and cmd.exe and either passes them the explicit code to run, or a path to a file. In its simplest model, Salt uses the return value of the cmd.exe or powershell.exe process to decide if the task succeeded or failed.</p>
  
  <p>What I'm wondering is, what controls the return value in each case? Is it just the exit code of the last command executed by the shell, unless you explicitly call "<strong>exit</strong>" with a return code? </p>
  
  <p>I know in Powershell you have <strong>$?</strong> and <strong>$lastexitcode</strong>, which have different uses. I'm wondering whether this complicates things or not. Is the return code of the powershell.exe different depending on whether the last command executed is a PowerShell function or Cmdlet, or a WIN32 binary?</p>
  
  <p>Are the rules the same for a script file vs. an explicit command?</p>
  
  <p>i.e.</p>
  
  <pre><code>PowerShell -Command Write-Host "Foo"
  </code></pre>
  
  <p>vs. </p>
  
  <pre><code>PowerShell -File script.ps1
  
  cmd /c echo foo
  </code></pre>
  
  <p>vs.</p>
  
  <pre><code>cmd /c test.bat
  </code></pre>
  
  <p>Perhaps it's really simple, but I've seen some examples around like:-</p>
  
  <ul>
  <li><code>cmd /c do_something &amp; exit %ERRORLEVEL%</code></li>
  <li><code>echo do_something; exit $lastexitcode | powershell -command -</code></li>
  </ul>
  
  <p>I'd love to know what the catches are to getting this error handling correct.</p>