0

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?

1 Answers1

0

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you, how can I define the `at` for `at task creation/modification` ? because it asks me for it. `cmdlet New-ScheduledTaskTrigger at command pipeline position 1 Supply values for the following parameters: At:` . –  Jan 07 '23 at 18:30
  • Thanks again for the updated answer, perfect as always! I was reading the DateTime struct to supply it with a DateTime type variable https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-7.0 because I just noticed that in Microsoft docs they say what the type of each parameter should be and I wasn't paying attention to that or rather was having a hard time finding a reference to those types. –  Jan 07 '23 at 18:43
  • 1
    My pleasure, @Jameschad; I've added the `-Once` and `-At` arguments, and `-At` comes with a pitfall - please see my update. – mklement0 Jan 07 '23 at 18:53