How can I run a PowerShell task at logon and repeat it every three minutes?
Asked by
MellowCedar42
I'm registering a PowerShell scheduled task that should start when a user logs in and then run Automation.ps1 every three minutes indefinitely. My current task uses New-ScheduledTaskTrigger -AtLogOn, but adding -RepeatIndefinitely and -RepetitionInterval does not work because those options cannot be combined directly with the logon trigger. What is the best way to configure this repetition?
Answers
Another practical approach is to create an ordinary one-time trigger whose repetition interval is three minutes, then copy its Repetition property onto the logon trigger: $logonTrigger = New-ScheduledTaskTrigger -AtLogOn; $repeatTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 3) -RepetitionDuration ([TimeSpan]::MaxValue); $logonTrigger.Repetition = $repeatTrigger.Repetition. Register the task using $logonTrigger.
Reply to this answer
You can construct the repetition pattern yourself and assign it to the logon triggerโs Repetition property. For example, create the trigger with New-ScheduledTaskTrigger -AtLogOn, then create an MSFT_TaskRepetitionPattern CIM instance with an interval such as [System.Xml.XmlConvert]::ToString((New-TimeSpan -Minutes 3)) and assign it to $trigger.Repetition before registering the task.
Reply to this answer
The built-in trigger parameters donโt let you combine -AtLogOn with an indefinite repetition interval. One option is to create the task in the graphical Task Scheduler first, configure the logon trigger and repetition there, and then export or inspect the resulting XML. You can use that XML when registering the task from PowerShell.
Reply to this answer
If the script is meant to run continuously, you could start it once at logon and have the script perform its work inside a loop with Start-Sleep -Seconds 180. However, a long-running loop can be less manageable than a scheduled task, and a service may be more appropriate if this needs to run reliably in the background.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions