Search code examples
powershellscheduled-taskswindows-task-schedulerwindows-11powershell-7.3

How can I create a scheduled task using PowerShell that runs every x minutes or x hours?


Using PowerShell 7.3.1, so can't use Register-ScheduledJob. without having to directly modify scheduled task XML files, since they are stored in 3 different places, how can I create a scheduled task in Windows that runs every x hours or x minutes.

I've done this in GUI

enter image description here

and I want to do something like that in PowerShell.

I've checked out this similar question, but it's incomplete for my situation.

Reading New-ScheduledTaskTrigger info, can't seem to find a parameter for each of them.

this is all I could figure out

$trigger = New-ScheduledTaskTrigger -RepetitionInterval "PT5M" 

another idea, if it's actually impossible to do what I want with native PowerShell, what if I create my task with PowerShell and a placeholder trigger like at startup, then use schtasks.exe to configure the trigger according to the screenshot I uploaded?

if that's doable, what are the command(s) for using schtasks.exe to modify the trigger like in the screenshot?


Solution

  • You need to pass [timespan] instances to the relevant parameters of the New-ScheduledTaskTrigger cmdlet, which you can construct with the New-TimeSpan cmdlet, for instance.

    $trigger = 
      New-ScheduledTaskTrigger `
        -Once -At (Get-Date).AddSeconds(5) `
        -RandomDelay (New-TimeSpan -Seconds 30) `
        -RepetitionInterval (New-TimeSpan -Minutes 5)
    

    Note:

    • -Once -At (Get-Date).AddSeconds(5) starts the task once, 5 seconds from now.

      • New-ScheduledTaskTrigger seemingly offers no way to specify the "At task creation / modification" option shown in your screenshot (the only non-time-related options are -AtLogon and -AtStartup, the latter referring to the system's startup), and it is imperative that the -At value lie in the future for the task to actually start, hence the 5-second delay - this isn't foolproof, but unless your system is under exceptionally heavy load, this should do.
    • -At expects a [datetime] instance, and Get-Date without arguments returns the current point in time.