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

C# 使用ValidateSet为强制Cmdlet参数提供默认值,c#,visual-studio-2010,powershell,business-objects,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 defaul

假设使用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
PS..\bin\Debug>get logontoken
cmdlet在命令管道位置1获取LogonToken
提供以下参数的值:
服务器名称:服务器
身份验证:
用户名:Username
密码:********
Get LogonToken:无法验证参数“Authentication”上的参数。这个
参数“”不属于集合“secEnterprise、secLDAP、secWinAD”
由ValidateSet属性指定。提供集合中的参数
然后重试该命令。在第1行char:1
+得到logontoken
+ ~~~~~~~~~~~~~~
+CategoryInfo:InvalidData:(:)[Get LogonToken],参数BindingValidationException
+FullyQualifiedErrorId:参数ArgumentValidationError,PsEnterprise.GetLogonToken
如何为使用
验证集的强制参数指定默认值?

您不能

必须为强制参数提供一个值。在提示处按Enter表示您给出的是空字符串或null<代码>验证集
与此无关。即使没有验证,也不会通过在提示下按Enter键来指定默认值


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

请修复标题中的键入:
manditory
我认为将参数设置为可选,然后在构造函数中提供默认值是一个好的选择;选项卡完成似乎不会列出
authentication
参数的有效值。@craig使用
ValidateSet
应该允许选项卡完成;我不知道为什么这不起作用。tab completion在32位或64位版本的shell或ISE中都不起作用。@craig我以前没有用C#编写cmdlet。编译后(可能是编译成DLL?),如何让PowerShell找到它?
PS>Import Module path\to\PsCmdletAssembly.DLL
是最简单的方法。您还可以在PSD1文件中引用程序集:
requiredAssemblys=@('PsCmdletAssembly')
。最后,您可以将一个类添加到provide中,该类派生自
System.ComponentModel.PsSnapIn
,然后使用
installutil.exe
(选择与项目的Targetr框架相对应的类)进行注册。