为带有ValidateSet的强制性Cmdlet参数提供默认值

本文关键字:参数 默认值 Cmdlet 强制性 ValidateSet | 更新日期: 2023-09-27 18:05:06

假设有一个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
}

调用cmlet:

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的强制参数分配默认值?

为带有ValidateSet的强制性Cmdlet参数提供默认值

你不能。

强制参数必须提供一个值。在提示符下按Enter意味着你给出了一个空字符串或null;ValidateSet和它没有任何关系。即使没有验证,也不会在提示符下按Enter键来分配默认值。

你可以让它成为可选的,然后给它一个默认值,但是如果你在调用cmdlet时不提供它,它将使用默认值,并且不会提示。