4. Automating PowerShell Scripts - Powershell
4.1 Creating Scheduled Tasks with PowerShell Scripts
Overview
Scheduling PowerShell scripts is a critical task for system administrators who need to automate routine monitoring and maintenance activities. This guide provides comprehensive instructions for creating scheduled tasks across different versions of Windows PowerShell.
Windows PowerShell 2.0 (Windows 7 or Windows Server 2008 R2)
For systems running PowerShell 2.0, you must use the Task Scheduler module to create scheduled jobs. Follow these steps:
Module Installation and Task Creation
# Import the Task Scheduler module
Import-Module TaskScheduler
# Create a new task
$task = New-Task
$task.Settings.Hidden = $true
# Add task action to execute the PowerShell script
Add-TaskAction -Task $task -Path C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
-Arguments "-File C:\Scripts\GroupMembershipChanges.ps1"
# Set daily trigger at 10:00 AM
Add-TaskTrigger -Task $task -Daily -At "10:00"
# Register the scheduled job
Register-ScheduledJob -Name "Monitor Group Management" -Task $task
Windows PowerShell 3.0 and 4.0 (Windows Server 2012 R2 and Above)
In newer PowerShell versions, Microsoft introduced more streamlined cmdlets for task scheduling:
Advanced Task Creation with System Account
# Define task trigger (daily at 10:00 AM)
$Trigger = New-ScheduledTaskTrigger -At 10:00am -Daily
# Specify system account for elevated privileges
$User = "NT AUTHORITY\SYSTEM"
# Define task action
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe"
-Argument "C:\PS\StartupScript.ps1"
# Register the scheduled task
Register-ScheduledTask -TaskName "MonitorGroupMembership"
-Trigger $Trigger
-User $User
-Action $Action
-RunLevel Highest
-Force
Additional Trigger Options
PowerShell offers several versatile trigger configurations:
-AtStartup: Executes the task during Windows startup-AtLogon: Triggers the task when a user signs in-Once: Runs the task a single time (with optional repetition interval)-Weekly: Executes the task once per week
Limitations
While PowerShell provides robust scheduling capabilities, it has some constraints:
- Event-based triggers are not directly supported through PowerShell cmdlets
- More complex event-triggered scripts require additional configuration
- For intricate event scheduling, the traditional Task Scheduler tool remains more flexible
Best Practices
- Always use specific, full paths for script locations
- Leverage system account for administrative tasks when appropriate
- Test scheduled scripts in a controlled environment before production deployment
- Implement logging and error handling within your scheduled scripts