This week we are looking at enumerations: what they are, and how you can benefit from them.
In the previous tips, we looked at enumerations, and here is a quick tip how you can suppress error messages generated by cmdlets with a minimum of code.
This line generates errors when run by a non-Administrator because you cannot access process details of processes owned by other users:
PS> Get-Process -FileVersionInfo
Since the errors are benign and unavoidable, you might want to silence them:
PS> Get-Process -FileVersionInfo -ErrorAction SilentlyContinue
This is perfect syntax for scripts. When you run code interactively, you are free to use dirty tricks to shorten the keyboard input, and write:
PS> Get-Process -FileVersionInfo -ea 0
“-ea” is an alias name for the –ErrorAction parameter, and the number 0 is the equivalent of the enumeration value for SilentlyContinue.
To find out the alias names for a parameter, use this:
PS> (Get-Command -Name Get-Process).Parameters["ErrorAction"].Aliases ea
To find out the numeric value of an enumeration value, first determine the data type the parameter needs:
PS> (Get-Command -Name Get-Process).Parameters["ErrorAction"].ParameterType.FullName System.Management.Automation.ActionPreference
Next, convert the parameter to an integer:
PS> [int][System.Management.Automation.ActionPreference]::SilentlyContinue 0
So if you’d like to create a shortcut for the parameter value “Ignore” instead of “SilentlyContinue”, try this:
PS> [int][System.Management.Automation.ActionPreference]::Ignore 4
The difference between “SilentlyContinue” and “Ignore” is that they both suppress error output, but “SilentlyContinue” still continues to write the suppressed errors to the special PowerShell variable $error.
From now on, in interactive PowerShell you could now suppress errors with the option “Ignore” like this, too:
PS> Get-Process -FileVersionInfo -ea 4
Please note: you can use these shortcuts in scripts, too, but you should avoid that. Scripts should always use default PowerShell for a maximum of clarity and readability.