liveBook · Manning

New-ScheduledTaskTrigger

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

New-ScheduledTaskTrigger is a PowerShell cmdlet that creates a trigger describing when a scheduled task runs.

New-ScheduledTaskTrigger creates the schedule definition for a Windows scheduled task. Choose a trigger frequency, such as once, daily, weekly, or at logon, before combining it with an action and registering the task. section 3.2.2

Daily log-file cleanup

$Trigger = New-ScheduledTaskTrigger -Daily -At 8am $Action = New-ScheduledTaskAction -Execute "C:\Program Files\PowerShell\7\pwsh.exe" -Argument '-File "C:\Scripts\Invoke-LogFileCleanup.ps1"' Register-ScheduledTask -TaskName "PoSHAutomation\LogFileCleanup" -Trigger $Trigger -Action $Action -User 'NT AUTHORITY\SYSTEM' The trigger handles timing; the action launches PowerShell with the script and its arguments, while registration creates the task for unattended execution. 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

Inspect the complete trigger, executable, argument string, action, task identity, and registration sequence. section 3.2.2

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Explains trigger frequencies and parameters, then stops short of detailed trigger internals.
Examples
Uses an 8 a.m. daily trigger for a log-file cleanup script.
What it assumes
Assumes PowerShell scripting familiarity and uses the Windows-included ScheduledTasks module.
What you can do after
Operate/configure unattended scheduled scripts by defining a trigger and registering it with an action.
How it connects
Connects scheduled task triggers with scheduled task actions and task registration.

This explainer was generated by Manning's knowledge graph from the text of Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.