PowerShell by Example: Scheduled Jobs
Automating background tasks with this code example demonstrating job registration, triggers, options, and result retrieval using the PSScheduledJob module.
Code
# Create a trigger for 3 AM daily
$trigger = New-JobTrigger -Daily -At "3:00AM"
# Set options (e.g., wake to run, run elevated)
$options = New-ScheduledJobOption -WakeToRun -RunElevated
# Register the scheduled job
Register-ScheduledJob -Name "DailyBackup" -ScriptBlock {
Compress-Archive -Path "C:\Data" -DestinationPath "C:\Backups\$(Get-Date -Format 'yyyyMMdd').zip"
} -Trigger $trigger -ScheduledJobOption $options
# List registered jobs
Get-ScheduledJob
# Check job history and results
Get-Job -Name "DailyBackup" | Receive-Job -KeepExplanation
PowerShell Scheduled Jobs provide a hybrid automation solution that combines the flexibility of background jobs with the reliability of the Windows Task Scheduler. Unlike standard background jobs that disappear when the session closes, scheduled jobs are registered with the Task Scheduler and persist across reboots. They run independently of any active user session and store their results (output, errors, and status) on disk, allowing administrators to retrieve execution history at any time using standard job cmdlets like Receive-Job.
Creating a scheduled job involves three main components: the script block or file to execute, a trigger defining when it runs, and options controlling the execution environment. The New-JobTrigger cmdlet allows for complex schedules, including daily, weekly, or event-based triggers (like system startup or user logon). The New-ScheduledJobOption cmdlet offers fine-grained control, such as waking the computer to run the task, running only when on AC power, or requiring elevated privileges. This modular approach makes it easy to define robust automation logic.
Managing these jobs is seamless within PowerShell. You can use Get-ScheduledJob to inventory registered tasks and Unregister-ScheduledJob to remove them. Because they are ultimately Windows Scheduled Tasks, they also appear in the Task Scheduler GUI under MicrosoftWindowsPowerShellScheduledJobs. This dual visibility is excellent for troubleshooting. Best practices include implementing robust error handling within the script block and ensuring that any required modules are available in the system context where the job executes.
- Use
Register-ScheduledJobfor persistent, unattended automation - Define execution schedules with
New-JobTrigger - Retrieve past execution results with
Receive-Job - Configure power and security settings via
New-ScheduledJobOption
Code Breakdown
New-JobTrigger creates a schedule object (e.g., daily at 3 AM).New-ScheduledJobOption configures advanced settings like running elevated.Register-ScheduledJob creates the task using the trigger and options.Receive-Job -Keep retrieves job output without deleting the history.
