craig craig - 1 year ago 138
PowerShell Question

Suppy a default value to a mandatory Cmdlet parameter with a ValidateSet

Assuming a Cmdlet class:

[System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Get, "LogonToken")]
public class GetLogonToken : System.Management.Automation.Cmdlet

// constructor
public GetLogonToken()
// set default auth.
this.Authentication = "secWinAD";

// addtional properties omitted

[System.Management.Automation.Parameter(Position = 1, Mandatory = true)]
[ValidateSet("secEnterprise", "secLDAP", "secWinAD")]
public string Authentication
get { return authentication; }
set { authentication = value; }

// setting authentication here has no effect either
private string authentication;

// addtional code omitted


Calling the Cmdlet:

PS ..\bin\Debug> get-logontoken

cmdlet Get-LogonToken at command pipeline position 1
Supply values for the following parameters:
ServerName: SERVER
Authentication: <hit enter>
Username: USERNAME
Password: ********
Get-LogonToken : Cannot validate argument on parameter 'Authentication'. The
argument "" does not belong to the set "secEnterprise,secLDAP,secWinAD"
specified by the ValidateSet attribute. Supply an argument that is in the set
and then try the command again.At line:1 char:1
+ get-logontoken
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-LogonToken], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,PsEnterprise.GetLogonToken

How do I assigned a default value to a mandatory parameter that uses a

Answer Source

You can't.

A mandatory parameter must have a value supplied. Hitting Enter at the prompt means you're giving an empty string or null; ValidateSet doesn't have anything to do with it. Even if there was no validation, a default value wouldn't be assigned by hitting Enter at that prompt.

You can make it optional, and then give it a default value, but if you don't supply it when you call the cmdlet, it will use the default and won't prompt.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download