Register-ScheduledTask creates or registers Windows Task Scheduler tasks from PowerShell. Define a trigger, action, and execution identity, then pass them to the cmdlet. The ScheduledTasks module is included with Windows, so no additional installation is required. section 3.2.2
Build a task in four operational stages:
- Create a trigger with New-ScheduledTaskTrigger, such as a daily run at 8 a.m. section 3.2.2
- Create an action with New-ScheduledTaskAction, using the PowerShell executable and a single argument string containing the script path and parameters. section 3.2.2
Listing 3.1 Creating a scheduled task
$Trigger = New-ScheduledTaskTrigger -Daily -At 8am #1
$Execute = "C:\Program Files\PowerShell\7\pwsh.exe" #2
$Argument = '-File ' + #3
'"C:\Scripts\Invoke-LogFileCleanup.ps1"' +
' -LogPath "L:\Logs" -ZipPath "L:\Archives"' +
' -ZipPrefix "LogArchive-" -NumberOfDays 30'
$ScheduledTaskAction = @{ #4
Execute = $Execute
Argument = $Argument
}
$Action = New-ScheduledTaskAction @ScheduledTaskAction
$ScheduledTask = @{ #5
TaskName = "PoSHAutomation\LogFileCleanup"
Trigger = $Trigger
Action = $Action
User = 'NT AUTHORITY\SYSTEM'
}
Register-ScheduledTask @ScheduledTask
A complete daily log-cleanup registration defines the trigger, PowerShell executable, quoted script arguments, task path, and SYSTEM identity. section 3.2.2
