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?
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?
As long as you aren't logged on as the user that will run the task then it should work just fine now.
Open Start. Search for PowerShell, right-click the top result, and select the Run as administrator option. (Optional) Type the following command to confirm the task exists and press Enter: Get-ScheduledTask -TaskName "TAKS-NAME" In the command, make sure to replace "TAKS-NAME" with the name of the task.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With