Last active
May 15, 2022 21:18
-
-
Save karlgluck/777c6a15ec78e946d93e2d55ec00c1cb to your computer and use it in GitHub Desktop.
Example of how to wait for a scheduled task to finish running
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Trigger = New-JobTrigger -Once -At (get-date).AddSeconds(5) | |
$JobOptions = New-ScheduledJobOption -StartIfOnBattery -RunElevated | |
$Job = Register-ScheduledJob -Name "TaskName" -Trigger $Trigger -ScheduledJobOption $JobOptions ` | |
-ScriptBlock { | |
Sleep 5 | |
} | |
# From https://docs.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-error-and-success-constants?redirectedfrom=MSDN | |
Set-Variable -Name "SCHED_S_TASK_HAS_NOT_RUN" -Value 0x00041303 -Option Constant | |
Set-Variable -Name "SCHED_S_TASK_RUNNING" -Value 0x00041301 -Option Constant | |
Set-Variable -Name "SCHED_S_TASK_SUCCESS" -Value 0x0 -Option Constant | |
do { | |
Sleep 1 | |
$ResultCode = (Get-ScheduledTask -TaskName "TaskName" | Get-ScheduledTaskInfo).LastTaskResult | |
switch ($ResultCode) | |
{ | |
$SCHED_S_TASK_HAS_NOT_RUN { Write-Host "Waiting to run the task" } | |
$SCHED_S_TASK_RUNNING { Write-Host "Task is running!" } | |
$SCHED_S_TASK_SUCCESS { Write-Host "Task completed" } | |
default { Write-Host "Error! $ResultCode" } | |
} | |
} while (@($SCHED_S_TASK_HAS_NOT_RUN, $SCHED_S_TASK_RUNNING) -contains $ResultCode) | |
$Job | Unregister-ScheduledJob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment