Skip to end of metadata
Go to start of metadata

Exit Code Handling with PowerShell

The exit code of a PowerShell script is usually expected as the result of the execution of the script. However, the program powershell.exe returns the exit code of the execution of the powershell.exe itself - and this in most cases 0.

To retrieve the effective exit code of the script, that script has to be terminated with an exit() function and as parameter the variable $lastexitcode (or any other value/variable for the exit code).

The example below shows how it works:

 <?xml version="1.0" encoding="ISO-8859-1"?>
 <job title="How to get the exit code from a powershell script"
     name="PowerShellExitCode">
    <script language="shell">
        <![CDATA[
 powershell.exe -noprofile -command "write-output test; exit 123 "
 echo %errorlevel%
 exit %errorlevel%
        ]]>
     </script>
     <run_time/>
 </job>

 

The result of this job is visible in the log file:

 [debug9] SCHEDULER-918  state=running_process (never)
  [info]   C:\Program Files (x86)\Scheduler>powershell -noprofile -command "write-output test; exit 123 " 
 [info]   test 
 [info]   C:\Program Files (x86)\Scheduler>echo 123  
 [info]   123 
 [info]   C:\Program Files (x86)\Scheduler>exit 123 
 [ERROR]  SCHEDULER-280  Process terminated with exit code 123 (0x7B)

The statement exit %errorlevel% passes the exit code to JobScheduler. If this statement is missing then JobScheduler will not know about the exit code and will assume that it is zero (0).

See also

 

 

Write a comment…