Categories

ErrorAction and WarningAction

You’ve all probably done something like this:

£> Get-Process -Name xyz
Get-Process : Cannot find a process with the name "xyz". Verify the process name and call the cmdlet again.
At line:1 char:1
+ Get-Process -Name xyz
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (xyz:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

 

First though of many people is to do this

Get-Process -Name xyz -ErrorAction silentlycontinue

Now, thats not good as you don’t know that an error has occurred.  Its better to deal with it rather than suppress it so you wrap it in a try-catch:

£> try {
>> Get-Process -Name xyz -ErrorAction Stop
>> }
>> catch{
>> "oops"
>> }
>>
oops

In reality you would want to do more than say “oops”

There are a number of situations where cmdlets give you a warning rather than an error. if you want to suppress them use –WarningAction.  It has the same options as –ErrorAction

SilentlyContinue. Suppresses the warning message and continues
executing the command.

Continue. Displays the warning message and continues executing
the command. "Continue" is the default value.

Inquire. Displays the warning message and prompts you for
confirmation before continuing execution. This value is rarely
used.

Stop. Displays the warning message and stops executing the
command.

More details in about_Common_Parameters

Leave a Reply