I need two scheduled tasks to be created with powershell that will run a powershell script each.
One should trigger at 08:00 every day and run every two hours. So at 10:00 ,12:00, 14:00 etc.. The other at 9 every day and run every two hours. So at 11:00 ,13:00, 15:00 etc..
If the user is not logged, the tasks should still be triggered as soon as he logs in. Lets say he logs in 9:35 this will trigger both tasks. How can they not run simultaneously?
I tried to add delay to one of them but there is a chance the delay will be 0
A solution can be:
- When they run simultaneously they check if this is the case somehow and one of the exits. Or,
- Some other method of ensuring they dont intercept
$taskAction1 = New-ScheduledTaskAction -Execute 'Powershell.exe' -argument "-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File $script1"
$taskAction2 = New-ScheduledTaskAction -Execute 'Powershell.exe' -argument "-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File $script2"
$taskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -Hidden -DontStopIfGoingOnBatteries
$taskTrigger = New-ScheduledTaskTrigger -AtLogOn
$taskTriggerWithDelay = New-ScheduledTaskTrigger -AtLogOn -RandomDelay 00:15:00
Register-ScheduledTask -User System -Action $taskAction1 -Trigger $TasKTrigger -TaskName "Task1" -RunLevel Highest -Settings $TaskSettings -f | Out-Null
Register-ScheduledTask -User System -Action $taskAction2 -Trigger $taskTriggerWithDelay -TaskName "Task2" -RunLevel Highest -Settings $TaskSettings -f | Out-Null
$trigger= Get-ScheduledTask -TaskName Task1
$trigger.Triggers.repetition.Interval = "PT2H"
$trigger.Triggers.repetition.duration = ""
$trigger | Set-ScheduledTask | Out-Null
$trigger= Get-ScheduledTask -TaskName Task2
$trigger.Triggers.repetition.Interval = "PT2H"
$trigger.Triggers.repetition.duration = ""
$trigger | Set-ScheduledTask | Out-Null