Creating Windows Scheduled Tasks with PowerShell
If you are looking at running tasks on a schedule, PowerShell can help you manage the Windows Task Scheduler. Using PowerShell Scheduled Tasks cmdlets you can create and automate administrative tasks such as backups and updates. This guide will get you started with PowerShell’s task scheduling, so you can boost your efficiency through automation.
Creating a New Scheduled Task
The New-ScheduledTask cmdlet can be used to create a scheduled task with PowerShell. With this cmdlet, you can specify the name, description, trigger, action, settings, and principal of the task.
Below is a basic example of creating a scheduled task that runs a PowerShell script every day at 10:00 AM:
# Define the trigger
$trigger = New-ScheduledTaskTrigger -Daily -At 10am
# Define the action
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\Scripts\MyScript.ps1"
# Define the settings
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries
# Define the principal
$principal = New-ScheduledTaskPrincipal -UserId "DOMAIN\User" -LogonType Password
# Create the task
New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal
| Register-ScheduledTask -TaskName "MyDailyTask" -User "DOMAIN\User" -Password "P@ssw0rd"
This code will create a scheduled task named “MyDailyTask” which runs the script C:\Scripts\MyScript.ps1 as the user DOMAIN\User with the password P@ssw0rd. The task will start when the system is available, even if it is on battery power and will run every day at 10:00 AM, unless it is disabled or deleted.
Managing Scheduled Tasks
To manage scheduled tasks with PowerShell, you can use various cmdlets that start with Get-, Set-, Enable-, Disable-, Start-, Stop-, and Unregister-.
For example, we can use the following commands to perform some common operations:
# Get all the scheduled tasks on the system
Get-ScheduledTask
# Get a specific scheduled task by name
Get-ScheduledTask -TaskName "MyDailyTask"
# Set the description of a scheduled task
Set-ScheduledTask -TaskName "MyDailyTask" -Description "This is my daily task"
# Enable or disable a scheduled task
Enable-ScheduledTask -TaskName "MyDailyTask"
Disable-ScheduledTask -TaskName "MyDailyTask"
# Start or stop a scheduled task
Start-ScheduledTask -TaskName "MyDailyTask"
Stop-ScheduledTask -TaskName "MyDailyTask"
# Unregister or delete a scheduled task
Unregister-ScheduledTask -TaskName "MyDailyTask" -Confirm:$false
These are some of the basic commands used to create and manage Windows scheduled tasks using PowerShell.
For more information and examples, you can refer to the official documentation of each cmdlet at the following link
https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/?view=windowsserver2022-ps
Newsletter
Join our newsletter