在非交互模式下更改凭据的行为

时间:2017-11-29 19:33:34

标签: powershell credentials powershell-v5.0

给定一个函数,它接受一个参数来抑制用户输入的提示(例如NonInteractive),是否有任何方法可以改变[System.Management.Automation.Credential()]的行为,如果它将一个用户名作为字符串传递给它抛出异常而不是提示输入密码?

function Test-NonInteractiveCredential {
    Param(
        [Parameter()]
        [PSCredential]
        [System.Management.Automation.Credential()] 
        $Credential = [PSCredential]::Empty
        ,        
        [Parameter()]
        [Switch]$NonInteractive
    )
    if ($Credential -eq [PSCredential]::Empty) {
        "no credentials specified"
    } else {
        "User: $($Credential.username); Pass: $($Credential.GetNetworkCredential().Password)"
    }
}

注意:我尝试使用PowerShell自己的命令行NonInteractive参数进行测试;但即使PS仍然提示。

powershell -noninteractive -command "function demo{param([System.Management.Automation.Credential()][PSCredential]$cred)process{$cred -eq $null;$cred.username}}; demo -cred 'demoUser'"

这是我提出的最好的解决方法:

function Test-NonInteractiveCredential {
    [CmdletBinding(DefaultParameterSetName = 'Interactive')]
    Param(
        [Parameter(ParameterSetName = 'Interactive')]
        [PSCredential]
        [System.Management.Automation.Credential()] #only included on the interactive version; so the non-interactive version would error if only a string were given
        $Credential = [PSCredential]::Empty
        ,        
        [Parameter(ParameterSetName = 'NonInteractive')]
        [PSCredential]
        $NonInteractiveCredential = [PSCredential]::Empty #we can't have a parameter with the same name
        ,        
        [Parameter(ParameterSetName = 'NonInteractive')]
        [Switch]$NonInteractive
    )
    if ($PSCmdlet.ParameterSetName -eq 'NonInteractive') {
        $Credential = $NonInteractiveCredential 
    }
    if ($Credential -eq [PSCredential]::Empty) {
        "no credentials specified"
    } else {
        "User: $($Credential.username); Pass: $($Credential.GetNetworkCredential().Password)"
    }
}

...但这并不理想,因为我们必须有一个单独的参数(即我们不能在两个参数集中都包含Credential参数,因为该属性只能在一个参数中使用,并且据我所知,没有办法修改每个参数集的这种行为。

注意:这是一个来自好奇心/纯粹学术的问题;我正试图解决没有现实世界的问题。

0 个答案:

没有答案