
π This article includes 2 downloadable practice files β
In this article
Writing a quick one-liner in the console is easy; writing an unattended production script that executes reliably every night at 2:00 AM on an enterprise server requires proper logging, strict error handling, and automated scheduling via Windows Task Scheduler.
Basic Level: Structured Error Handling with Try, Catch, and Finally
By default, PowerShell uses Non-Terminating Errors for minor issues (such as a file not found), meaning the script prints an error message but continues running the next line. To catch errors in a try / catch block, set the -ErrorAction Stop parameter (or = 'Stop'):
# Enterprise error handling template
= 'Stop'
try {
Write-Host "Connecting to network share..."
= Get-Content -Path "\fileserverdatadaily.txt"
Write-Host "Read $(.Count) records."
}
catch [System.IO.FileNotFoundException] {
Write-Warning "File missing: $(.Exception.Message)"
}
catch {
Write-Error "Unexpected fatal failure: $(.Exception.Message)"
# Log error to event log or logfile
}
finally {
Write-Host "Cleanup: releasing locked resources."
}
Intermediate Level: Enterprise File Logging with Timestamps
Unattended scripts should write clean, standardized log files so system administrators can audit outcomes the next morning:
function Write-Log {
param(
[Parameter(Mandatory=)][string],
[ValidateSet("INFO", "WARN", "ERROR")][string] = "INFO",
[string] = "C:LogsDailyAutomation.log"
)
= (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
= "[] [] "
Add-Content -Path -Value
}
# Example usage inside scripts:
Write-Log "Automation pipeline initiated." "INFO"
Write-Log "Database connection latency exceeded 500ms." "WARN"
Expert Level: Creating Windows Scheduled Tasks via PowerShell
Instead of manually clicking through the GUI Task Scheduler, register automated scheduled tasks programmatically using PowerShell’s ScheduledTasks module:
# 1. Define the action: launch powershell with script
= New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File C:ScriptsDailyReconcile.ps1"
# 2. Define the trigger: Daily at 02:00 AM
= New-ScheduledTaskTrigger -Daily -At "02:00AM"
# 3. Define execution settings: stop if runs longer than 1 hour
= New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1)
# 4. Register task under SYSTEM account or Service Account
Register-ScheduledTask `
-TaskName "Daily_Finance_Reconcile" `
-Action `
-Trigger `
-Settings `
-User "NT AUTHORITYSYSTEM" `
-Description "Automated overnight financial data reconciliation script."
Production Script Checklist
- β
= 'Stop'declared at top of script. - β
All external paths use full UNC or absolute paths (never relative paths like
.data). - β Structured logging with timestamps on every step and failure.
- β
No hardcoded passwords or API keys (use
Get-Credentialor Windows Credential Manager / Azure Key Vault). - β Execution time limits configured on Scheduled Tasks to prevent hung processes.
π Practice files for this article
β¬ Download all 2 files (ZIP Β· 829 B)
- π₯οΈps-06-scheduled-task.ps1Lesson code file.β¬ PS1 Β· 766 B
- πps-06-scheduled-task-output.txtOutput from our test run.β¬ TXT Β· 63 B
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.