L6. Files, Error Handling, and Debugging
Work safely with the filesystem, understand terminating vs non-terminating errors, and use try/catch/finally, -ErrorAction, and debugging habits that prevent destructive mistakes.
Filesystem Basics
PowerShell uses providers. The filesystem is one provider, but registry, certificate, and variable drives can appear through similar commands.
Get-Location
Get-ChildItem -Path . -File
New-Item -ItemType Directory -Path .\lab
Copy-Item .\input.txt .\lab\input-copy.txt
Remove-Item .\lab\input-copy.txt -WhatIf
-WhatIf is one of the most important safety habits in PowerShell. Use it before commands that change or delete resources.
Error Types
PowerShell has terminating and non-terminating errors. Many cmdlets report a non-terminating error and continue. To catch those errors in try/catch, use -ErrorAction Stop.
try {
Get-Item -Path .\missing.txt -ErrorAction Stop
} catch {
[pscustomobject]@{
Message = $_.Exception.Message
Category = $_.CategoryInfo.Category
}
} finally {
'Cleanup or final logging goes here'
}
Debugging Habits
- Use
Set-StrictMode -Version Latestin scripts while learning. - Use
Write-Verbosefor optional diagnostic messages. - Use
$PSStyle.OutputRendering = 'PlainText'when clean logs matter. - Build scripts in small tested sections.
- Prefer
Join-Pathover string-concatenating file paths.
Lab
- Create a directory named
ps-lab. - Create three text files inside it.
- Write a script that counts files and catches missing-path errors.
- Run destructive commands first with
-WhatIf. - Add
Write-Verbosemessages and test with-Verbose.
- ✓Use -WhatIf before commands that modify or delete resources
- ✓Use -ErrorAction Stop to convert many non-terminating cmdlet errors into catchable errors
- ✓try/catch/finally is the standard structure for recoverable failures
- ✓Join-Path is safer than manually concatenating paths
- ✓Verbose messages help debugging without polluting structured output
1. Why might a catch block not run for a cmdlet error?
2. What is the purpose of -WhatIf?
Recommended: Pluralsight
This free course covers the theory. Pluralsight adds structured video courses, hands-on Azure labs, and timed practice exams to make it stick before exam day.