Receiving Error Level from PowerShell Script

by Apr 29, 2015

Here is a quick script illustrating how a PowerShell script can send back a numeric status code to the caller:

$exitcode = 123

$p = Start-Process -FilePath powershell -ArgumentList "-command get-process; exit $exitcode" -PassThru
Wait-Process -Id $p.Id

'External Script ended with exit code ' + $p.ExitCode

If you call the script directly (without Start-Process) from within PowerShell, the numeric return value is exposed in $LASTEXITCODE instead:

$exitcode = 199

powershell.exe "get-process; exit $exitcode"

'External Script ended with exit code ' + $LASTEXITCODE 

And if you run a PowerShell script from within a batch file or VBScript, the numeric return value can be received in the environment variable %ERRORLEVEL%, just as if PowerShell was a console application – which powershell.exe in fact is.

Twitter This Tip! ReTweet this Tip!