Get the red out by adding routines to capture errors and then control when they are revealed. Never use $ErrorActionPreference in the head of your scripts. If you do, good luck with debugging! Instead use -ErrorAction SilentlyContinue inline with the command(s). This will capture non-terminating errors (you can make them terminating with the -ErrorAction Stop option).
Add in the -ErrorVariable with a variable name and you chose when and where to reveal any issues. Example

PS C:\> Get-process -Id 23,42 -ErrorAction SilentlyContinue -ErrorVariable MyErrors
PS C:\> $MyErrors.CategoryInfo | Select TargetName, Category

TargetName Category
———- ——–
23 ObjectNotFound
42 ObjectNotFound

Note the $Variable.CategoryInfo | Select TargetName, Category. This is much more elegant than the more traditional

$MyErrors | Foreach-Object { $_.CategoryInfo | Select-Object TargetName, Category }

These are the properties of CategoryInfo:
{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

For Terminating Errors, I personally don’t normally do anything with them because I want to see the information (any issues should have been addressed during creation/testing of the function). However, this is where Try{}Catch{}Finally{} work. Use the contents of the $Error built-in variable to return specific bits of information in your catch or finally block.

#tags: Error, Errors, Powershell, ErrorAction, ErrorVariable, ErrorActionPreference, Powershell



One thought on “ErrorAction In Action

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s