Introduction
Error handling helps your script keep running even when something goes wrong. It stops the script from crashing and lets you fix or ignore problems safely.
try {
# Code that might cause an error
} catch {
# Code to run if an error happens
} finally {
# Code that runs no matter what
}try {
Get-Content 'file.txt'
} catch {
Write-Host 'File not found, continuing...'
}try {
Remove-Item 'C:\temp\important.txt'
} catch {
Write-Host 'Cannot delete file, skipping.'
}try {
# Try to divide by zero, which causes an error
$result = 10 / 0
Write-Host "Result is $result"
} catch {
Write-Host "Oops! You can't divide by zero."
}
Write-Host "Script continues after error handling."try {
Get-Item 'C:\nonexistentfile.txt'
} catch {
Write-Output 'File not found, continuing script.'
}
Write-Output 'Script finished.'try {
Get-Item 'C:\nonexistentfile.txt' -ErrorAction SilentlyContinue
} catch {
Write-Output 'Error caught.'
}
Write-Output 'Done.'Pass the test and this pattern moves unknown