Windows – Access Denied when creating a scheduled task with powershell and the com schedule.service object

powershellscheduled-taskwindows

I have a powershell script that creates a scheduled task using a call to RegisterTask via the Schedule.Service com object.

Essentially:

$ts = new-object -com Schedule.Service
$ts.Connect()
$rootfolder = $ts.GetFolder("\")
$taskXml = Get-Content "Task.xml"
$rootfolder.RegisterTask("\Maintenance", $taskXml, 6, "LOCAL SERVICE", $null, 5)

This works fine on my local machine (windows 7, and I am a local admin)

When I try this on the machine it will be run on, the RegisterTask call fails with ACCESS_DENIED.

However, if I run a command prompt as administrator, then powershell.exe -file myscript.sps1 it works fine and adds the task.

I have ensured that the user that it is running under has permissions to write to the Tasks folders in %windir% and %windir%/system32

The user is in the Administrators group, which is puzzling, what else do I need to do to give the user the permissions to create scheduled tasks? It seems that just adding them to the local administrators group isn't enough.

EDIT: I have logged onto the server as the user that will be running the script. I can successfully import the xml file into the Task Scheduler UI addin manually.

Best Answer

Since Powershell 4.0 you can use the ScheduledTask module to create Scheduled tasks without the use of the com-object and easier reading and writing.

Example:

 $A = New-ScheduledTaskAction -Execute "Taskmgr.exe"
 $T = New-ScheduledTaskTrigger -AtLogon
 $P = New-ScheduledTaskPrincipal "Laptop\Administrator"
 $S = New-ScheduledTaskSettingsSet
 $D = New-ScheduledTask -Action $A -Principal $P -Trigger $T -Settings $S
 Register-ScheduledTask T1 -InputObject $D

The first command uses the New-ScheduledTaskAction cmdlet to assign the variable $A to the executable file tskmgr.exe.

The second command uses the New-ScheduledTaskTrigger cmdlet to assign the variable $T to the value AtLogon.

The third command assigns the variable $P to the principal of the scheduled task, Contoso\Administrator.

The fourth command uses the New-ScheduledTaskSettingsSet cmdlet to assign the variable $S to a task settings object.

The fifth command creates a new task and assigns the variable $D to the task definition.

The sixth command (hypothetically) runs at a later time. It registers the new scheduled task and defines it by using the $D variable.

Dont forget the run the code as Administrator. Source.