Search code examples
powershellwindows-task-scheduler

Windows Task Scheduler not returning $LASTEXITCODE from a Powershell script


I have a script that just calls Exit 1. But, when this script is run via Windows Task Scheduler, I get either a return code of 0, or 2147942401, but I never get the expected 1. Details below.

Script Content

Exit 1

Windows Task Definition:

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command '. C:\myscript.ps1; exit $LastExitCode'

Run Result

When I run this task, the task history shows, Task Scheduler successfully completed task "\My task" , instance "{3f344413-46c2-4419-b46b-85896f241d60}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe" with return code 0.

If I alter the Windows Task definition to use double quotes instead of single quotes, I get a different result.

Edited Windows Task Definition

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command ". C:\myscript.ps1; exit $LastExitCode"

New Result

Task Scheduler successfully completed task "\My task" , instance "{c44082a8-56fe-4615-aad0-70dca8b71881}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe" with return code 2147942401.

How can I get 1 for my task's return code? Do I need to run 2147942401 through some kind of convertor to get 1? Or is there something else at work here?

Thanks.


Solution

  • get-scheduledtaskinfo worked for me with powershell c:\script.ps1 (-command is the default):

    set-content c:\script.ps1 'exit 1' # or 'exit $error.count'
    $action = New-ScheduledTaskAction powershell c:\script.ps1
    Register-ScheduledTask script.ps1 \ $action -force # overwrite
    start-scheduledtask script.ps1
    while ((Get-ScheduledTask script.ps1).State -ne 'Ready') {
      Write-Verbose -Message 'Waiting on scheduled task...'; sleep 1 }
    
    get-scheduledtaskinfo script.ps1
    
    LastRunTime        : 10/23/2022 10:29:29 AM
    LastTaskResult     : 1
    NextRunTime        :
    NumberOfMissedRuns : 0
    TaskName           : script.ps1
    TaskPath           :
    PSComputerName     :
    

    Some crazy bit math to get the exit code from task scheduler from @mklement0's comments under here: How get task scheduler to detect failed error code from powershell script:

    function get-taskschedexitcode ($tasknum) {$tasknum -band -bnot 0x80070000}
    get-taskschedexitcode 2147942401
    
    1
    
    
    1 -bor 0x80070000L
    
    2147942401
    

    Or

    2147942401 | % tostring x  # convert to hex
    
    80070001
    
    
    0x80070001 - 0x80070000  # get exit code
    
    1
    
    
    2147942401 - 2147942400
    
    1
    
    
    -join '2147942401'[-2..-1]
    
    01