Powershell - Create Scheduled Task to run as local system / service

前端 未结 3 1884
生来不讨喜
生来不讨喜 2021-02-07 10:33

Can anyone tell me how to create a scheduled task using powershell that runs as the local system or local service?

Everything works great except the call to ITaskFolder.

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 10:53

    For those who can use PowerShell 3.0 on Windows 8 or Windows Server 2012, new cmdlets will let you do it in a simple way when registering your scheduled task with the cmdlet Register-ScheduledTask and as argument -User "System"

    Here is a scheduled task created entirely with PS, its purpose is to restart a service My Service, using the SYSTEM account, 3 minutes after the system has started:

    $taskname = "Restart My Service"
    $taskdescription = "Restart My Service after startup"
    $action = New-ScheduledTaskAction -Execute 'Powershell.exe' `
      -Argument '-NoProfile -WindowStyle Hidden -command "& Restart-Service -displayname \"My Service\""'
    $trigger =  New-ScheduledTaskTrigger -AtStartup -RandomDelay (New-TimeSpan -minutes 3)
    $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
    Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskname -Description $taskdescription -Settings $settings -User "System"
    

    NB: you will need to run powershell as an administrator for that script.

提交回复
热议问题