PowerShell Lesson 6: Robust Scripts, Error Handling and Scheduled Tasks

PowerShell Lesson 6: Robust Scripts, Error Handling and Scheduled Tasks featured illustration

πŸ“Ž This article includes 2 downloadable practice files ↓

⏱ 2 min readUpdated 11 November 2026

πŸ“˜ PowerShell Beginner Course Β· Lesson 6 of 6

In this article
  1. Basic Level: Structured Error Handling with Try, Catch, and Finally
  2. Intermediate Level: Enterprise File Logging with Timestamps
  3. Expert Level: Creating Windows Scheduled Tasks via PowerShell
  4. Production Script Checklist
  5. Continue learning

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.

Advertisement

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:

Advertisement
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-Credential or 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)

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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Comment