A script that works on your test server will one day meet a server that’s offline, a file that’s locked, or an account without rights. Good error handling decides whether that becomes a clear log line – or a half-finished change nobody notices.
Two kinds of errors
- Terminating errors stop the command (and your script, unless caught).
- Non-terminating errors print red text and carry on – for example,
Get-Service -Name Spooler, DoesNotExistreturns Spooler and complains about the other.
try/catch only catches terminating errors. That surprises everyone once.
Make errors catchable with -ErrorAction Stop
try {
Get-Service -Name DoesNotExist -ErrorAction Stop
'This line does not run'
}
catch {
Write-Warning "Could not find the service: $($_.Exception.Message)"
}
Inside catch, $_ is the error record. Useful parts:
$_.Exception.Message # the message
$_.InvocationInfo.ScriptLineNumber
$_.CategoryInfo.Category # e.g. ObjectNotFound, PermissionDenied
To make every cmdlet in a script stop on error, set this at the top:
$ErrorActionPreference = 'Stop'
finally – always clean up
$session = New-PSSession -ComputerName SRV01
try {
Invoke-Command -Session $session -ScriptBlock { Restart-Service Spooler } -ErrorAction Stop
}
catch {
Write-Warning "SRV01: $($_.Exception.Message)"
}
finally {
Remove-PSSession $session # runs whether it worked or not
}
Keep going across many servers
When you loop through servers, catch per server so one failure doesn’t stop the rest, and record the result:
$results = foreach ($s in $servers) {
try {
$svc = Invoke-Command -ComputerName $s -ScriptBlock { Get-Service -Name Spooler } -ErrorAction Stop
[pscustomobject]@{ Server = $s; Status = $svc.Status; Error = $null }
}
catch {
[pscustomobject]@{ Server = $s; Status = 'FAILED'; Error = $_.Exception.Message }
}
}
$results | Export-Csv C:\Temp\spooler-check.csv -NoTypeInformation
Now the report shows every server, including the ones that failed and why.
Simple logging
A small function writes timestamped lines to a file and the screen:
function Write-Log {
param([string] $Message, [ValidateSet('INFO','WARN','ERROR')] [string] $Level = 'INFO')
$line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
Add-Content -Path $LogFile -Value $line
Write-Host $line
}
$LogFile = "C:\Temp\Logs\cleanup_$(Get-Date -Format yyyyMMdd_HHmm).log"
New-Item -ItemType Directory -Path (Split-Path $LogFile) -Force | Out-Null
Write-Log 'Cleanup started'
For a full record of everything a script printed, use a transcript:
Start-Transcript -Path C:\Temp\Logs\run.txt
# ... script ...
Stop-Transcript
Never log passwords or secrets. Check that your error messages don’t print connection strings or credentials either.
Exit codes for schedulers and pipelines
Task Scheduler, Jenkins and GitHub Actions decide success by the exit code. End your script with:
if ($results.Status -contains 'FAILED') { exit 1 } else { exit 0 }
FAQ
Should I use -ErrorAction SilentlyContinue?
Only when an error is genuinely expected and harmless (e.g. checking whether something exists). Hiding errors everywhere hides real problems.
What’s next
Next: PowerShell remoting – run commands on many servers.
Practise this topic
Test yourself with free questions on this topic – instant answers and explanations.
Start practice questionsPowerShellError HandlingLoggingIntermediate