Create scheduled task w/ Admin access from PowerShell?


I have a script that sets up the (AWS) instance (joins domain, hardening etc).

Part of it (load GPO backups, create OUs and users) needs to run after a reboot, so I figured I create a scheduled task for it.

But I can't get it to get the access it needs!

$psexe = Join-Path $PSHOME powershell.exe
$T = New-ScheduledTaskTrigger -AtStartup
$P = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest -LogonType ServiceAccount
$S = New-ScheduledTaskSettingsSet
$A = New-ScheduledTaskAction -Execute $psexe -Argument "-NoProfile -NonInteractive -NoLogo -ExecutionPolicy Unrestricted -File C:\Windows\Temp\install_gpo.ps1"
$D = New-ScheduledTask -Action $A -Principal $P -Trigger $T -Settings $S
Register-ScheduledTask -TaskName "Install GPO" -InputObject $D -ErrorAction Ignore

The script itself is fairly simple:

Start-Transcript -path C:\log-install_gpo.txt
Import-GPO -BackupGpoName LogonBanner -TargetName LogonBanner -Path C:\Windows\Temp\GpoBackups -CreateIfNeeded

Running the task (!) manually from the task scheduler GUI and looking at the log file, I see:

Import-GPO : Access is denied. (Exception from HRESULT: 0x80070005
At C:\Windows\Temp\install_gpo.ps1:2 char:1
+ Import-GPO -BackupGpoName LogonBanner -TargetName LogonBanner -Path C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Import-GPO], UnauthorizedAcce
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Gro

So it seems that the 'System' user doesn't have access to do what I want/need! Not sure why that is, I specify the highest RunLevel and Unrestricted execution policy..

Running the Import-GPO command in an elevated PS shell works just fine!

I can't run it as Administrator, because that would require a password (that doesn't work anyway, Register-ScheduledTask refuses to accept that on the command line), I can't specify both -UserID and -GroupID (...\Administrator for example) at the same time.

I've tried using the RunOnce registry key, but that seem to work even less. Also, if I understand the docs for that correctly, it is only run when a/any user logs in, which might never happen! This is (supposed to be) a "headless server" so no-one should ever login to it..

I'm at a loss to what to try next.

asked on Stack Overflow Apr 7, 2020 by Turbo Fredriksson • edited Jul 5, 2020 by Martijn Pieters

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0