By default, PowerShell writes errors to the error stream and continues executing the script rather than stopping. You can change this behavior by setting the $ErrorActionPreference variable to Stop, which causes PowerShell to halt the script whenever an error occurs.
PowerShell has two kinds of commands: cmdlets and native commands. For example, Get-ChildItem is a cmdlet, and git is a native command. The $ErrorActionPreference variable has controlled cmdlet behavior since the first version of PowerShell. In PowerShell 7.3, the $PSNativeCommandUseErrorActionPreference variable was introduced to provide the same control for native commands.
Setting $ErrorActionPreference to Stop halts the script when a cmdlet throws an error. Setting $PSNativeCommandUseErrorActionPreference to true extends this behavior to native commands. A good practice is to set both variables at the beginning of your scripts:
PowerShell
# Stop the script when a cmdlet or a native command fails
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
You can override $ErrorActionPreference for a specific cmdlet using the -ErrorAction parameter. For instance, the following command continues even if Get-ChildItem fails:
PowerShell
Get-ChildItem dummy -ErrorAction SilentlyContinue
To bypass $PSNativeCommandUseErrorActionPreference for a specific native command, use the & { } syntax to run the command inside a script block. Set $PSNativeCommandUseErrorActionPreference to false within the block; the variable reverts to its previous value when the block exits.
PowerShell
& {
# Disable $PSNativeCommandUseErrorActionPreference for this scriptblock only
$PSNativeCommandUseErrorActionPreference = $false
robocopy.exe dummy1 dummy2
if ($LASTEXITCODE -gt 8) {
throw "robocopy failed with exit code $LASTEXITCODE"
}
}
#Additional resources
Do you have a question or a suggestion about this post? Contact me!