Powershell: Set a Scheduled Task to run when user isn’t logged in

I’m not a fan of embedding my credentials into a script (which a few other example here do) and additionally, you generally can’t do this from something like Packer or some other system/configuration automation or in a cloud provider with an pseudo-randomly generated password. Plus, generally, I feel hardcoding your credentials into a script or command or task is “bad practice” and can then easily leak.

There is a better way to do this which I want to recognize that Aeyoun mentioned in a comment in this thread but didn’t go into details about which is to properly set the principal to run as the system user. I dove into and resolved this, and this is how I schedule the task as the SYSTEM user that runs automatically and in the background and doesn’t depend on a user being logged in or not.

This below set of commands is what I’ve used in a handful of places where I’ve had to schedule in the background a critical task that needed administrator access. Hope it helps you!

$action = New-ScheduledTaskAction -Execute foo.exe -Argument "bar baz"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration ([Timespan]::MaxValue)
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -MultipleInstances Parallel

Register-ScheduledTask -TaskName "tasknamehere" -TaskPath "\my\path" -Action $action -Trigger $trigger -Settings $settings -Principal $principal

Leave a Comment