c# - 使用 ValidateSet 为强制 Cmdlet 参数提供默认值

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

最佳答案

你不能。

强制参数必须提供一个值。在提示符下按 Enter 意味着您输入的是空字符串或 null; ValidateSet 与它没有任何关系。即使没有验证,也不会通过在该提示下按 Enter 来分配默认值。

您可以将其设置为可选,然后为其提供默认值,但如果您在调用 cmdlet 时不提供它,它将使用默认值并且不会提示。

关于c# - 使用 ValidateSet 为强制 Cmdlet 参数提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39257111/

相关文章:

visual-studio-2010 - 如何为 .js 文件扩展 vs2010 编辑器上下文菜单?

c++ - C++ : . NET Framework 警告的 Visual Studio 设置

powershell - Get-WmiObject需要太多时间才能执行

powershell - 更新导出的csv powershell的列值

c# - 是否可以在 Web API 服务中托管两个不同的 Odata 模型

c# - 通过两个代理的 HttpWebRequest

c# - Protobuf 继承和泛型

c# - 安排要发送的电子邮件

powershell - 删除脚本中的别名

c# - Stimulsoft Pdf 报告动态 unicode 字符串