Skip to content

Instantly share code, notes, and snippets.

@nyanhp
Created June 25, 2020 11:35
Show Gist options
  • Save nyanhp/058dadd36b6a5ef02ca12444f8a5015d to your computer and use it in GitHub Desktop.
Save nyanhp/058dadd36b6a5ef02ca12444f8a5015d to your computer and use it in GitHub Desktop.
Self-rescheduling task
$taskScript = {
# Do your stuff, start the service, ...
Start-Service -Name TheCrashingService
$triggers = @(
New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(12)
New-ScheduledTaskTrigger -AtLogOn -User 'someone'
)
$task = Get-ScheduledTask -TaskName YourScheduledTask
# Reset triggers to AtLogon trigger
if ($task.Triggers.Count -eq 2)
{
$triggers = New-ScheduledTaskTrigger -AtLogOn -User 'someone'
}
Set-ScheduledTask -TaskName YourScheduledTask -Trigger $triggers
}
$taskScript.ToString() | Set-Content .\MyTask.ps1
$triggers = New-ScheduledTaskTrigger -AtLogOn -User 'someone'
$action = New-ScheduledTaskAction -Execute (Join-Path $PSHome powershell.exe) -Argument "-File `"$(Resolve-Path .\MyTask.ps1)`""
$task = New-ScheduledTask -Action $action -Trigger $triggers -Description 'Does things'
$task | Register-ScheduledTask -TaskName YourScheduledTask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment