Is there any way to catch exceptions thrown by exe files in powershell scripts? Is there any way to catch exceptions thrown by exe files in powershell scripts? powershell powershell

Is there any way to catch exceptions thrown by exe files in powershell scripts?


Exe's use exitcodes to return error status instead of .NET exceptions. A workaround is to check the $lasterrorexitcode. If you want to make use of try/catch blocks you can issue a throw statement if the lasterrorcode is not equal to zero. Note: One thing to be cautious of--some exe's use non-zero error codes to return a status other than error.

Here's an example:

Wrap in try/catch block

try {    $result = some-exe.exe    if ($lastexitcode -ne 0) {                $result = $result -join "`n"        throw "$result `n"    }}catch {  write-error "$_"}


(Possibly) clever ways around the issue (first two involve sending keystroke to thrown exception dialog box to dismiss it automatically)

  1. Use WASP powershell module (on Codeplex) to query for existence of error dialog for a few seconds after you execute the EXE, and if dialog window exists then send key to dismiss it

  2. Use system.diagnostics.process to start EXE, and register some combination of the 3 possible events: Disposed, ErrorDataReceived, and Exited, to distinguish between EXE throwing an exception or not.

  3. If you can load the EXE as an assembly, and then execute its Main method, then you can could catch an exception via try/catch.