Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Try Catch

Tags:

powershell

I've a simple powershell script below which basically executes the abc.exe (console application) with few arguments.

& abc.exe ar1 ar2

abc.exe file is .net so it has it's own exception handler.

Whenever abc.exe throws exception I would like the Powershellscript to catch and log/echo.

Could someone help me how to achieve above.

like image 765
Nil Pun Avatar asked Jul 09 '26 02:07

Nil Pun


1 Answers

No.

The exception in abc.exe will bubble up to main method, not any more. But you can check the ERRORLEVEL of abc.exe by looking at $LASTEXITCODE. (Check this)

What you should do:

  • Your abc.exe, as any exe, should return errorlevel 0 if everything was ok and other number in case of error
  • Abc.exe main method could write an error message in case of problem. This way when you invoke it from a PowerShell script you will see the error message in console and later your script will check for errorlevel.

Additionally, you can also use different exitcodes for errorlevels in abc.exe to provide some information to PowerShell script. For example these are 7zip error levels.

  • 0 --> No error
  • 1 --> Warning
  • 2 --> Fatal error
  • 7 --> Command line error
  • 8 --> Not enough memory for operation
  • 255 --> User stopped the process
like image 179
Oscar Foley Avatar answered Jul 11 '26 19:07

Oscar Foley