使用ValidateSet为必需的Cmdlet参数提供默认值

3
假设有一个 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的必选参数分配默认值?


请修正标题中的拼写错误:manditory - wOxxOm
1个回答

4

无法做到。

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

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


我认为将参数设置为可选的,然后在构造函数中提供默认值是一个不错的选择;因为似乎无法通过制表符补全来列出“authentication”参数的有效值。 - craig
@craig 使用 ValidateSet 应该允许使用制表符自动完成;我不确定为什么这不起作用。 - briantist
选项卡自动完成在 shell 或 ISE 的 32 位或 64 位版本中均无法正常工作。 - craig
@craig 我之前没用 C# 写过 cmdlet。一旦你编译它(预计会变成 DLL?),你怎么让 PowerShell 找到它呢? - briantist
PS> Import-Module path\to\PsCmdletAssembly.dll 是最简单的方法。您还可以在 PSD1 文件中引用该程序集:RequiredAssemblies = @('PsCmdletAssembly')。最后,您可以添加一个从 System.ComponentModel.PsSnapIn 派生的类到提供程序中,然后使用 installutil.exe(选择与您项目目标框架对应的版本)进行注册。 - craig
@craig 如果你使用 ipmo assembly.dll,那么你可以运行 gcm -mod MyModule 并查看列出的 cmdlet 吗?如果可以的话,我不明白为什么它们不会自动补全,但是我对二进制 cmdlet 的经验很少。也许这可以作为一个新问题。 - briantist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接