L6. Files, Error Handling, and Debugging
Course outlineLesson 6 of 10
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 -Force
Set-Content -Path .\input.txt -Value 'Lab input' -Encoding utf8NoBOM
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.
Text Files and Encoding
PowerShell 7 text output defaults to utf8NoBOM; Get-Content also defaults to UTF-8 when no BOM identifies another encoding. Use explicit encoding for file interchange, especially when scripts also run in Windows PowerShell 5.1, whose defaults differ.
Set-Content -Path ./lab/names.txt -Value 'Ada', 'Lin' -Encoding utf8NoBOM
Get-Content -Path ./lab/names.txt -Encoding utf8
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'
}Use -ErrorAction Stop on a specific cmdlet when that failure should enter catch. The default $ErrorActionPreference is Continue; setting it to Stop affects non-terminating PowerShell errors in its scope. Save and restore it in finally if temporarily changing it. Native program exit codes do not automatically behave like cmdlet exceptions: check $LASTEXITCODE when running external tools.
finally runs for cleanup when execution leaves try/catch, including after a handled error or return. It cannot guarantee cleanup if the process is forcibly terminated.
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.
Use these in a disposable script with no credentials in variables or output. Set-PSDebug -Trace 1 traces lines; -Trace 2 also traces variable assignments and function calls. Disable tracing afterward. For an interactive breakpoint, save the script first and point Set-PSBreakpoint at an executable line:
Set-PSDebug -Trace 1
Get-Item -Path ./lab
Set-PSDebug -Off
# After saving ./count-files.ps1, pause when its first executable line runs
$bp = Set-PSBreakpoint -Script ./count-files.ps1 -Line 1
./count-files.ps1
# At the debugger prompt, use c to continue
Remove-PSBreakpoint -Breakpoint $bp
Lab
- Use the lab directory created above. Save ./count-files.ps1 in the working directory, starting with [CmdletBinding()] and param() on separate lines so -Verbose is supported.
- 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.
References
- Try, catch, finally semantics
- Error preference behavior
- PowerShell character encoding defaults
- Get-Content encoding
- Set-PSDebug tracing
- Set-PSBreakpoint
Continue Learning
Build scripts and modules Continue PowerShell practice- ✓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?