PowerShell supports full .NET exception handling. By default, errors in PowerShell are "Non-Terminating" (the script turns red but keeps running). To catch them, you must force them to be "Terminating" using -ErrorAction Stop.
$logFile = "C:\MissingDir\log.txt"
try {
Write-Output "Attempting read..."
# Force 'Stop' if reading fails to trigger the Catch block
$content = Get-Content -Path $logFile -ErrorAction Stop
}
catch [System.UnauthorizedAccessException] {
Write-Warning "You do not have permission to read this file."
}
catch {
# Catch any other error
Write-Error "A catastrophic failure occurred: $($_.Exception.Message)"
}
finally {
Write-Output "Process sequence finalized."
}