0
0
PowerShellscripting~5 mins

ErrorAction parameter in PowerShell

Choose your learning style9 modes available
Introduction
The ErrorAction parameter helps you control what happens when a command runs into an error. It lets you decide if the script should stop, continue, or silently ignore errors.
When you want to stop a script if an important command fails.
When you want to try a command but ignore errors and keep going.
When you want to log errors but not show them on the screen.
When you want to handle errors yourself in a script.
When running commands that might fail but should not stop the whole script.
Syntax
PowerShell
Command -ErrorAction <Action>
Replace with one of: SilentlyContinue, Stop, Continue, Inquire, Ignore.
Use -ErrorAction to control error behavior for that specific command.
Examples
This tries to get a file but does not show any error if the file is missing.
PowerShell
Get-Item 'C:\file.txt' -ErrorAction SilentlyContinue
This stops the script if the file is not found.
PowerShell
Get-Item 'C:\file.txt' -ErrorAction Stop
This asks you what to do if an error happens.
PowerShell
Get-Item 'C:\file.txt' -ErrorAction Inquire
Sample Program
This script tries to get a file that does not exist. Because of -ErrorAction Stop, it jumps to catch block and prints a friendly message.
PowerShell
try {
    Get-Item 'C:\nonexistentfile.txt' -ErrorAction Stop
    Write-Output 'File found.'
} catch {
    Write-Output 'File not found. Handling error gracefully.'
}
OutputSuccess
Important Notes
SilentlyContinue hides errors but they still happen behind the scenes.
Stop lets you catch errors with try/catch blocks.
Continue shows errors but keeps running the script.
Summary
Use ErrorAction to control how PowerShell handles errors for commands.
Common values are SilentlyContinue, Stop, and Continue.
It helps make scripts more reliable and user-friendly.