Search code examples
windowspowershellscheduled-tasks

Create a scheduled task which runs every minute without the user being logged in using PowerShell


I'm trying to use PowerShell to create (and replace) a scheduled Windows task. I found the docs for the relevant PowerShell commands and as far as I can see, I have everything right:

$action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
$now = Get-Date
$interval = New-TimeSpan -Seconds 60
$forever = [System.TimeSpan]::MaxValue
$trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval -RepetitionDuration $forever
$settings = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName 'TEST' -InputObject $task

However, running this, I get a cryptic error:

Register-ScheduledTask : The task XML contains a value which is incorrectly formatted or out of range.

The error message is useless - how do I debug it?

  • What XML? At what path?
  • Which value?
  • What range?

This answer says to now use TimeSpan.MaxValue so I used a 100 years instead:

$forever = $now.AddYears(100) - $now # [System.TimeSpan]::MaxValue doesn't work

However, the error remains the same.

I googled around and found a suggestion to look into HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree, however, my task doesn't appear in there.

What to do?


Solution

  • Just don't set the -RepetitionDuration parameter at all. By default, it will do it indefinitely.

    $action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
    $now = Get-Date
    $interval = New-TimeSpan -Seconds 60
    $forever = [System.TimeSpan]::MaxValue
    $trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval 
    $settings = New-ScheduledTaskSettingsSet
    $task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
    Register-ScheduledTask -TaskName 'TEST' -InputObject $task
    

    Task created using the script above Task scheduler trigger

    As for your error, the complete error I had when attempting to execute your script was clear enough. It specifically indicated that the "Max" timespan was not an accepted value.

    Register-ScheduledTask : The task XML contains a value which is incorrectly formatted or out of range. (8,42):Duration:P99999999DT23H59M59S At line:8 char:1 + Register-ScheduledTask -TaskName 'TEST' -InputObject $task + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException + FullyQualifiedErrorId : HRESULT 0x80041318,Register-ScheduledTask