Q: If I have an error in a sub-PowerShell process, the parent Windows PowerShell process doesn't see the error or return an error--how can I fix this?

A: Consider a regular error in PowerShell:

  1. Throw "Error Here"

The PowerShell process would display the error, and you would be aware of the error.

Now consider:

  1. PowerShell {
  2. Throw "Error from within"
  3. }

The error would be unknown and wouldn't stop the parent PowerShell process. One easy solution is to set global error handling for PowerShell:

  1. $Global:ErrorActionPreference = "Stop"
  2. PowerShell {
  3. Throw "Error from within"
  4. }

Now an error in the sub-process will still throw an error in the parent PowerShell process.

Another option is to actually track error state using variables and pass those variables back as the result of a called PowerShell process. For example, within the sub-PowerShell process,I could use:

  1. $Global:ErrorActionPreference = "Stop"
  2. $ErrorState = 0
  3. $ErrorMessage = "No Error"
  4. Try{
  5. Throw "Error happened here"
  6. }
  7. Catch {
  8. $ErrorState = 1
  9. $ErrorMessage = $Error[0].Exception.ToString()
  10. }

Notice in the event of error, I set the error state and actual message into a variable. This could then be passed back to the calling PowerShell process.