2

我正在PowerShell中编写一些脚本,我想知道是否有一种方法可以“声明”参数“X”,就像声明参数“-Credential”一样,例如在Get-WMIObject cmdlet中。

让我更具体一点。几乎所有 cmdlet 中的 Credential 参数都是 PSCredential 对象。但是,参数可以是 PSCredential 对象,也可以是带有用户名的字符串对象。

[CmdletBinding()]
param ([Parameter(Mandatory = $false)]
       [System.Management.Automation.PSCredential]
       $Credential)

传递字符串时出现问题。当然,不能对参数进行参数转换。无法将类型“System.String”转换为类型 PSCrendential。

4

4 回答 4

5

试试这个:

param(
    [System.Management.Automation.Credential()]
    $Credential=[System.Management.Automation.PSCredential]::Empty
)

至于参数参数转换,请查看这个很棒的脚本:

http://poshcode.org/3024

于 2012-04-07T07:14:06.447 回答
1

更多信息:)

PowerShell 包含其中一种用于凭据的参数转换,因此,每当您编写具有 PSCredential 参数的脚本时,都应该使用 CredentialAttribute 来装饰它,如下所示:

param([Parameter(Mandatory = $false)]
      [System.Management.Automation.PSCredential]
      [System.Management.Automation.Credential()]$Credential =  [System.Management.Automation.PSCredential]::Empty)

这有点令人困惑,因为您省略了属性名称的“属性”部分(即:您不必指定[System.Management.Automation.CredentialAttribute()]),所以乍一看,它看起来像您'指定凭据类型两次。当然,实际上这是 PowerShell 中括号的另一种用法。要指定属性,您可以像使用类型一样使用方括号,但在其中使用括号(即使该属性不需要任何参数)。

http://huddledmasses.org/more-custom-attributes-for-powershell-parameters/

于 2012-04-10T20:34:40.020 回答
0

如果将函数参数声明为 [T] 类型,则在调用该函数时可以提供 [X] 类型的任何对象,其中 [T] 具有采用 [X] 类型的单参数构造函数。

换句话说,如果您可以从 [String] 构造 [T],则可以使用 [T] 或 [String] 调用该函数。

于 2012-04-05T21:53:37.363 回答
0

我就是这样做的。我这样声明参数:

[Parameter(Position=2)] [object]$Credential

然后在脚本的开头:

begin {
        Write-Verbose -Message "Starting  $($myinvocation.mycommand)"
        write-verbose -Message "Using volume $($volume.toUpper())"
        #convert credential to a PSCredential if a string was passed.
        if ( $credential -is [system.management.automation.psCredential]) {
            Write-Verbose "Using PSCredential for $($credential.username)"
        }
        ElseIf ($Credential) {
            Write-Verbose "Getting PSCredential for $credential"
            $Credential=Get-Credential $credential
        }
    } #Begin
于 2012-04-10T13:28:27.287 回答