使用ValidateSet

时间:2016-08-31 19:00:29

标签: c# visual-studio-2010 powershell business-objects

假设有一个Cmdlet类:

[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

}

调用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

如何为使用ValidateSet

的必填参数指定默认值

1 个答案:

答案 0 :(得分:2)

你不能。

必须参数必须提供值。在提示符处按Enter键意味着您给出一个空字符串或null; ValidateSet与此无关。即使没有验证,也不会通过在该提示符处按Enter键来分配默认值。

您可以将其设为可选项,然后为其指定默认值,但如果在调用cmdlet时未提供该值,则会使用默认值并且不会提示。