Errors: Terminating and Non-Terminating
Prerequisites: Advanced functions
PowerShell has two kinds of errors, and knowing the difference is the key to handling them.
- A non-terminating error reports a problem and carries on —
Get-Itemgiven three paths, one missing, still returns the other two. - A terminating error stops the command (and the script, unless caught).
'a.txt', 'c.txt' | ForEach-Object { Set-Content $_ 'x' }
Get-Item a.txt, b.txt, c.txt | Select-Object -ExpandProperty Name
'Still running'
a.txt
Get-Item: C:\demo\script.ps1:2
Line |
2 | Get-Item a.txt, b.txt, c.txt | Select-Object -ExpandProperty Name
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot find path 'C:\demo\b.txt' because it does not exist.
c.txt
Still running
The error was shown, but the other files were still returned and the script continued.
-ErrorAction
-ErrorAction controls what a command does with non-terminating errors:
| Value | Behavior |
|---|---|
Continue |
show the error and continue (the default) |
SilentlyContinue |
hide it and continue |
Stop |
turn it into a terminating error |
Ignore |
hide it completely (not even recorded) |
$item = Get-Item missing.txt -ErrorAction SilentlyContinue
$null -eq $item
True
$ErrorActionPreference = 'Stop' at the top of a script changes the
default for every command — a common choice for automation, so that
problems don't go unnoticed.
$Error and -ErrorVariable
Get-Item nope1.txt, nope2.txt -ErrorAction SilentlyContinue -ErrorVariable problems
$problems.Count
$problems[0].Exception.Message
$problems[0].CategoryInfo.Category
2
Cannot find path 'C:\demo\nope1.txt' because it does not exist.
ObjectNotFound
-ErrorVariable namecollects that command's errors (without the$).$Errorholds every error in the session, newest first.
Writing errors in your own functions
function Get-Square {
[CmdletBinding()]
param([Parameter(Mandatory)][object[]]$Value)
foreach ($v in $Value) {
if ($v -isnot [int]) {
Write-Error "'$v' is not a whole number"
continue
}
$v * $v
}
}
Get-Square -Value 3, 'x', 5 -ErrorAction SilentlyContinue
9
25
Write-Error— a non-terminating error: report and move on to the next item.throw— a terminating error: stop, because continuing makes no sense.