0
0
PowerShellscripting~5 mins

Terminating vs non-terminating errors in PowerShell

Choose your learning style9 modes available
Introduction
Errors happen when something goes wrong in a script. Knowing the difference between terminating and non-terminating errors helps you decide how your script should react.
When you want your script to stop immediately if a serious problem occurs.
When you want your script to keep running even if some small errors happen.
When you need to handle errors differently depending on how bad they are.
When debugging scripts to find out why something failed.
When writing scripts that manage files or system settings and need careful error control.
Syntax
PowerShell
Try {
  # Code that might cause an error
} Catch {
  # Code to handle terminating errors
}

# Non-terminating errors usually just show a warning and let the script continue
Terminating errors stop the script or the current command unless caught with Try/Catch.
Non-terminating errors show a message but let the script keep running.
Examples
This command causes a non-terminating error if the file doesn't exist. The script continues.
PowerShell
Get-Item 'C:\no_such_file.txt'
This forces a terminating error if the file doesn't exist, stopping the script unless caught.
PowerShell
Remove-Item 'C:\no_such_file.txt' -ErrorAction Stop
This catches the terminating error and handles it without stopping the whole script.
PowerShell
Try {
  Remove-Item 'C:\no_such_file.txt' -ErrorAction Stop
} Catch {
  Write-Host 'Caught a terminating error!'
}
Sample Program
This script shows a non-terminating error that lets the script continue, then a terminating error caught by Try/Catch to prevent the script from stopping.
PowerShell
Write-Host 'Start script'

# Non-terminating error example
Get-Item 'C:\no_such_file.txt'
Write-Host 'After non-terminating error'

# Terminating error example with Try/Catch
Try {
  Remove-Item 'C:\no_such_file.txt' -ErrorAction Stop
} Catch {
  Write-Host 'Caught a terminating error!'
}

Write-Host 'End script'
OutputSuccess
Important Notes
Use -ErrorAction Stop to turn non-terminating errors into terminating errors when needed.
Try/Catch blocks only catch terminating errors.
Non-terminating errors are useful when you want to log problems but keep going.
Summary
Terminating errors stop the script unless handled with Try/Catch.
Non-terminating errors show warnings but let the script continue.
You can control error behavior with -ErrorAction parameter.