Recently I needed a programmatic way to check valid arguments for a Cmdlet that were defined by a “ValidateSet”. I came across the article from Jeffrey Snover “Programmatic way to get valid string values for a parameter” but the mechanism did not seem to work (unless you start PowerShell with the “-Version 1” or “-Version 2” parameter). As this article is from 2006 and probably not for PowerShell v3 maybe something changed. I actually do not know. However I adapted the code to work with PowerShell v3 and still retrieve a valid list of arguments for a given “ValidateSet”.

Using the Cmdlet “Out-File” and its parmeter “Encoding” as the same example I change the code to this:

1. Retrieve the Cmdlet “Out-File”

$c = Get-Command "Out-File";

2. Get the parameter “Encoding”

# maybe check for the parameter first
# if(!$c.Parameters.ContainsKey('Encoding')) { Do-Something; }
$p = $c.Parameters['Encoding'];

3- Get its valid input parameters

 ($p.Attributes |? { $_ -is [System.Management.Automation.ValidateSetAttribute] }).ValidValues;

unknown string unicode bigendianunicode utf8 utf7 utf32 ascii default oem 

As a side note: The use of the “-is” operator seems to me actually “stronger” than to use a “-match” against the “typeid” string representation.

Leave a Reply

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

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.