0

I'm setting up scheduled tasks in Windows Server 2016 through Powershell (not through schtasks.exe).

$user = "Administrator"
$trigger = New-ScheduledTaskTrigger -Daily -At 0:00 
$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\forfiles.exe" -Argument '/p "C:\example"'
Register-ScheduledTask -Action $action -Trigger $trigger -User $user -TaskName "foobar"

The tasks do not run. Run only if user is logged in is enabled on the new tasks. I want to try to see if the tasks run if Run whether user is logged in or not is enabled.

I don't see anything in the New-ScheduledTaskSettingsSet documentation regarding this.

Is there a way to do this through Powershell?

5
  • If you want to run as logged in or not, then it can't run in the context of the user. It needs to run as system, not administrator. To do this, you can remove your $user line, add this line: $principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest and then in the register statement, remove -user $user and replace with -Principal $principal
    – Narzard
    Commented Dec 12, 2023 at 16:53
  • Please note, you may want to try running as NT AUTHORITY\LocalSYSTEM first before trying SYSTEM as localsystem has lesser privileges.
    – Narzard
    Commented Dec 12, 2023 at 17:01
  • I think NT AUTHORITY\LocalService could work as well. You will need to run PowerShell as administrator.
    – harrymc
    Commented Dec 12, 2023 at 17:06
  • 2
    Scheduled tasks can run in user context, but you need to provide the password for it to log on with. Use the same Register-ScheduledTask command as in the question, and just add -Password "password" for the associated user.
    – Cpt.Whale
    Commented Dec 12, 2023 at 17:45
  • @Narzard I think OPs question is to mimic the UI setting where you can indeed select your current user, and have it run as that user without being logged in. It can even run without storing the password (the UI has a checkbox to allow not storing the password)
    – Adarsha
    Commented Feb 21 at 18:07

1 Answer 1

0

Following Narzard's guidance - I am using this with success:

$user = "NT AUTHORITY\SYSTEM"
$trigger = New-ScheduledTaskTrigger -Daily -At 0:00 
$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\foobar.exe" -Argument '/baz "buzz"'
Register-ScheduledTask -Action $action -Trigger $trigger -User $user -TaskName "foobarbazbuzz" -Description "These tasks run"

There are some details on what this $user account signifies over at https://serverfault.com/questions/168752/windows-localsystem-vs-system.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .