New Scheduled Task - Run Not Logged In

Scripted Scheduled Task - Run Whether User is Logged On Or Not

I am trying to create a scheduled task via script that will run using a service account whether or not the user is logged on. I have read other articles, even one on this site, but the answer didn’t fix my problem. Here’s my code.

$A = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-file c:\ThisApp\ThisServiceScript.ps1"
$P = New-ScheduledTaskPrincipal -UserId 'MyDomain\SA-MyServiceAcct' -LogonType ServiceAccount
$T = New-ScheduledTaskTrigger -AtStartup
$S = New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval 2
$D = "Run service jobs."
$Tn = "Service Jobs"
Register-ScheduledTask -TaskName $Tn -Action $A -Trigger $T -Description $D -Principal $P

The problem is that I still have to log on, edit the task, click the button for “Run whether user is logged on or not” and type the password to save it.

I was under the assumption that using New-ScheduledTaskPrincipal and applying that principal made it so the task could run whether or not the user is logged on. It even says so on the technet article: New-ScheduledTaskPrincipal.

When you use a scheduled task principal, Task Scheduler can run the task regardless of whether that account is logged on.
Can this be done strictly in code, without having to edit the task afterward?

Thanks in advance,



Are you using a Group Managed Service Account? If so, $P should be:

$P = New-ScheduledTaskPrincipal -UserId 'MyDomain\SA-MyServiceAcct$' -LogonType Password

The username in the UserId parameter needs a $ at the end. The user account may need the ‘Logon as a batch job’ GPO setting as well.

Edit: I forgot to specifically mention to also change the LogonType to Password.