I\'m currently automating the creation of scheduled tasks via Powershell, and I\'m using the New-ScheduledTaskAction
, New-ScheduledTaskTrigger
, and
As I said in the original post, the SuperUser question above looked promising, but ultimately did not work with PSV4, and the example given in the post was basically a copy\paste job with almost no context.
I realized I could leverage Schtasks.exe from my Powershell script to handle the monthly aggregations, and it's fairly easy to set up, albeit somewhat tedious :
# set the trigger depending on time, span, and day
$runSpan = $task.SpanToRun;
if ($runSpan.Equals("Daily"))
{
$trigger = New-ScheduledTaskTrigger -Daily -At $task.TimeToRun
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $task.TaskName -User $Username -Password $Password -Description $task.Description
}
if ($runSpan.Equals("Weekly"))
{
$trigger = New-ScheduledTaskTrigger -Weekly -At $task.TimeToRun -DaysOfWeek $task.DayToRun
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $task.TaskName -User $Username -Password $Password -Description $task.Description
}
# script out SchTasks magic to create the monthly tasks
if ($runSpan.Equals("Monthly"))
{
$taskParams = @("/Create",
"/TN", $task.TaskName,
"/SC", "monthly",
"/D", $task.DayToRun,
"/ST", $task.TimeToRun,
"/TR", $filePath,
"/F", #force
"/RU", $Username,
"/RP", $Password);
# supply the command arguments and execute
#schtasks.exe $taskParams
schtasks.exe @taskParams
}
I'm using an in-script class to keep track of all the task properties ($task.TimeToRun
, $task.DayToRun
, etc.), iterating over a list of those, applying the Powershell implementation for daily and weekly tasks, then switching to SchTasks.exe for the monthly spans.
One thing I want to note, is that at first glance, I thought setting the user context under which the task runs could be achieved with the U
and P
arguments, but that is not the case. That specifies the creds that Schtasks.exe runs under - in order to set the user context for the task, you must use RU
and RP
.
In addition to the link above, these two were also very helpful :
http://coding.pstodulka.com/2015/08/02/programmatically-scheduling-powershell-scripts-in-task-scheduler/
https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx