Search code examples
powershellscheduled-tasksgmsa

Deploy gMSA account as task scheduler user account


I am trying to create a task on windows 2016 server, and need to deploy gMSA account as the log on account and below is the script i am using, i need to ensure that the option- "Run whether user is logged or not" gets selected,what change should be made to below code?

$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "NoProfile -ExecutionPolicy Unrestricted C:\Admin\Scripts\test.ps1 "
$trigger = New-ScheduledTaskTrigger -daily -At 5:05am
$Pri = New-ScheduledTaskPrincipal -UserId "Domain\gMSA" -LogonType ServiceAccount -RunLevel Highest
$task = New-ScheduledTask -Action $action -Trigger $trigger 
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Taskname" -Principal $Pric 

Solution

  • This is a similar request as the SO topic and answers / accepted answer.

    Set a Scheduled Task to run when user isn't logged in But since you are using a gMSA, you'd never know what that password is.

    So, you can create the task normally and then do say this...

    schtasks /change /TN \YourTaskName /RU DOMAIN\gMSA_Name$ /RP
    

    Or in pure PowerShell, you again set the Scheduled Task and then do this...

    New-ScheduledTaskPrincipal -UserID Domain\GMServiceAccount$ -LogonType Password
    

    See the details of the above here:

    Active Directory - Scheduled Tasks Using a gMSA