Creating Scheduled Tasks with PowerShell Scripts

Suppose that each day at 10 AM, we want to execute a PowerShell script that monitors changes to group membership in an Active Directory site.

In Windows PowerShell 2.0 (Windows 7 or Windows Server 2008 R2), to create a scheduled job, you must use the Task Scheduler module. Install the module by running the Import-Module TaskScheduler command, and then use the following script to create a task that will execute the PowerShell script named “GroupMembershipChanges.ps1” daily at 10 AM:

Import-Module TaskScheduler
$task = New-Task
$task.Settings.Hidden = $true
Add-TaskAction -Task $task -Path C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe –Arguments "-File C:\Scripts\GroupMembershipChanges.ps1"
Add-TaskTrigger -Task $task -Daily -At "10:00"
Register-ScheduledJob –Name "Monitor Group Management" -Task $task

Windows PowerShell 3.0 and 4.0 (Windows Server 2012 R2 and above) don’t include the Task Scheduler module, so this script will not work. Instead, PowerShell 3.0 and 4.0 include new cmdlets for creating scheduled tasks, New-ScheduledTaskTrigger and Register-ScheduledTask, which make creating a scheduled task much easier and more convenient. So let’s create a task that will execute our script daily at 10 AM using the system account (SYSTEM), which has elevated privileges:

$Trigger= New-ScheduledTaskTrigger -At 10:00am –Daily # Specify the trigger settings
$User= "NT AUTHORITY\SYSTEM" # Specify the account to run the script
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PS\StartupScript.ps1" # Specify what program to run and its parameters
Register-ScheduledTask -TaskName "MonitorGroupMembership" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force # Specify the name of the task

Other trigger options that could be useful in creating new tasks include:

  • -AtStartup — Triggers the task at Windows startup.
  • -AtLogon — Triggers the task when the user signs in.
  • -Once — Triggers the task once. You can set a repetition interval using the –RepetitionInterval parameter.
  • -Weekly — Triggers the task once a week.

Note that it is not possible to trigger execution “on an event” using these cmdlets; PowerShell scripts with “on an event” triggers are much more complicated. However, it is possible to do so with the Task Scheduler tool, so this is a real disadvantage of using PowerShell rather than Task Scheduler.