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:
Throw "Error Here"
The PowerShell process would display the error, and you would be aware of the error.
Now consider:
PowerShell { Throw "Error from within" }
The error would be unknown and wouldn't stop the parent PowerShell process. One easy solution is to set global error handling for PowerShell:
$Global:ErrorActionPreference = "Stop" PowerShell { Throw "Error from within" }
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:
$Global:ErrorActionPreference = "Stop" $ErrorState = 0 $ErrorMessage = "No Error" Try{ Throw "Error happened here" } Catch { $ErrorState = 1 $ErrorMessage = $Error[0].Exception.ToString() }
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.