Home > Software engineering >  How do I get the ErrorLevel from a process started via PowerShell Start-Process called from CMD?
How do I get the ErrorLevel from a process started via PowerShell Start-Process called from CMD?

Time:04-03

I'd like to be able to get the ErrorLevel of Process.exe from this example command:

C:\>PowerShell -NoP -C "Start-Process "C:\Process.exe""

If Process.exe exits with an ErrorLevel of 5, I'd like to be able to capture that via CMD, ideally in the %ErrorLevel% variable. I'm not proficient enough in PowerShell to do this.

CodePudding user response:

Use the following, assuming that C:\process.exe is a console application:[1]

PowerShell -NoP -C "C:\Process.exe; exit $LASTEXITCODE"

Note: If the executable path contains spaces, enclose it in '...'; if it contains ' itself, either escape the enclosed ' chars. as '', or enclose the path in \"...\" (sic) instead - see this answer for more information.

In order to get a process' exit code, you must wait for it to terminate.

Start-Process does not wait for termination by default, unless you add the -Wait switch - but then you'd also need -PassThru in order to return a process-information object whose .ExitCode property you'd need to report via exit.

Direct execution of the target executable, as shown above, (a) results in synchronous execution of console applications[1] to be begin with and (b) automatically reflects the process exit code in the automatic $LASTEXITCODE variable variable.

Without the exit $LASTEXITCODE statement, the process' exit code would be mapped to an abstracted exit code: 0 (success) would be reported as-is, but any nonzero exit code would be mapped to 1 - see this post for more information.

Either way, PowerShell's (powershell.exe's) exit code will be reflected in cmd.exe's dynamic %ErrorLevel% variable.


[1] If your application happens to be a GUI-subsystem application, you'll indeed need a Start-Process-based solution; as you've noted in a comment yourself, the solution would be:
PowerShell -NoP -C "exit (Start-Process 'C:\Process.exe' -Wait -PassThru).ExitCode"

  • Related