A scheduled task runs a PowerShell script without someone starting it manually. Define when it runs, what executable starts it, the script arguments, and the account context. For unattended automation, choose an account that has only the access the task needs. section 3.2.1 section 3.2.2
Access decisions determine whether an automation works safely. A task running as SYSTEM can work when its script, logs, and other resources are local. If the script or resources live on a network share, use a service account that can reach them; avoid a personal account, unrestricted shares, and broad per-computer access. section 3.2.1
Build a task from explicit configuration so the same automation can be deployed consistently:
- Create a trigger with New-ScheduledTaskTrigger. Supported examples include one-time, daily, weekly, and logon triggers. section 3.2.2
- Create an action with New-ScheduledTaskAction. Set Execute to the PowerShell executable, not the .ps1 file. section 3.2.2
- Pass -File, the script path, and script parameters as one argument string. Quote paths carefully, especially where spaces occur. section 3.2.2
- Register the task with Register-ScheduledTask, supplying its name, trigger, action, and run-as user. section 3.2.2
- Install custom PowerShell modules in a module path available to the account running the task so they can load at runtime. section 3.2.1
Daily log cleanup
A daily 8 a.m. cleanup task starts PowerShell 7, calls Invoke-LogFileCleanup.ps1 with log and archive paths, retains files for 30 days, and runs as NT AUTHORITY\SYSTEM. This arrangement fits an automation whose files and resources are local. section 3.2.1 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
This complete listing separates the daily trigger, PowerShell executable, quoted script arguments, action, and registration settings into reusable variables. section 3.2.2
For multi-computer deployment, either define tasks in PowerShell or export an existing task to XML and import it elsewhere. Scripted registration helps keep configurations consistent where Task Scheduler has no single console for scheduling across machines. Store automation tasks in a dedicated Task Scheduler folder to keep them distinct from unrelated tasks. section 3.2.2
