June 13, 2014

How to call a Powershell script from the command line and return an ERRORLEVEL

Sometimes you want to call a powershell script from the command line and get an ERRORLEVEL a the exit if an exception is throw in the script (ex: With a scheduled task).

In Powershell v2 you could do this :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop;exit $LastExitCode"

Unfortunately this does not work anymore in Powershell v4 (always return ERRORLEVEL 0). It looks like the $LastExitCode is not define anymore for a script by Powershell (only for an external process).  But Powershell seems to now behave as expected and exit with an ERRORLEVEL=1 if any error occurs in your script. So now, the following code should works :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop"

If you really want to check if your script was successful and return a special ERRORLEVEL, you should use the $? variable :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop;if ($?){exit 0}else{exit 99}"

Don’t forget :

  • To use dote-sourcing, the small dot (.) in  front of the script name.
  • To use the –command parameter instead of the –file parameter. The two parameters behave differently.
  • To set the –erroraction stop. If you keep the default value of continue, your script will not stop and the ERRORLEVEL will not be set to 1.

No comments:

Post a Comment