2

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.

Styris
  • 133
  • 1
  • 7
  • 1
    As an aside: Embedding `"` chars. inside an `"..."` string requires _escaping_ - see [this answer](https://stackoverflow.com/a/49060341/45375). – mklement0 Apr 02 '22 at 23:01

1 Answers1

2

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"

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you!! I was accomplish it along with `-Wait` using this command: `PowerShell -NoP -C "$psErr = (Start-Process 'C:\Process.exe'" -Wait -PassThru).ExitCode; exit $psErr"`. After that command, it's in `cmd`'s %ErrrorLevel% variable. – Styris Apr 02 '22 at 23:15
  • 1
    That works too, @Joe, but the solution in this answer is simpler - assuming that `process.exe` is a _console_ application. If not, your solution is indeed the right one. – mklement0 Apr 02 '22 at 23:20