Return Error from Sub-PowerShell Process

Return errors in different ways from sub-PowerShell processes.

John Savill

October 19, 2013

1 Min Read
Return Error from Sub-PowerShell Process

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.

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like