Powershell $ Credential对象可防止需要用户交互

时间:2018-11-20 13:47:00

标签: powershell

Hello StackOverflow!,

我正在尝试创建一个新对象,该对象也可以传递un / pwd,以便与正在使用的其余API通话时不需要用户交互。

Microsoft在以下位置提供了一个方便的示例(示例7):https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-credential?view=powershell-6

但是使用这种方法时,我收到以下信息:

    New-Object : Cannot find an overload for "PSCredential" and the argument 
    count: 
    "2".
    At line:17 char:15
    + ... redential = New-Object -TypeName 
    System.Management.Automation.PSCrede ...
    +                 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], 
    MethodException
    + FullyQualifiedErrorId : 
    ConstructorInvokedThrowException,Microsoft.PowerShel 
    l.Commands.NewObjectCommand

    Invoke-RestMethod : A positional parameter cannot be found that accepts 
    argument 
    '$null'.
    At line:21 char:1
    + Invoke-RestMethod -Method Get -Uri $uri $Credential #-Credential $cre 
    ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-RestMethod], 
    ParameterB 
    indingException
    + FullyQualifiedErrorId : 
    PositionalParameterNotFound,Microsoft.PowerShell.Com 
    mands.InvokeRestMethodCommand

只是为了验证我的代码,它与Microsoft示例基本相同:

    $Uri = 'A url to a rest api'
    $User = "A Username"
    $PWD = "A Password"
    $Credential = New-Object -TypeName 
    System.Management.Automation.PSCredential -ArgumentList $User, $PWD 


    #Invokes rest get request to rabbitmq uri                            
    Invoke-RestMethod -Method Get -Uri $uri $Credential      

收到错误后,我想我没有在传递New-Object命令,这是期望的吗?

感谢您的帮助。

谢谢

J

2 个答案:

答案 0 :(得分:1)

您需要使用以下密码输入SecureString

$User = "A Username"
$PWD = ConvertTo-SecureString -String "A Password" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User,$PWD)

Invoke-RestMethod -Method Get -Uri $uri -Credential $Credential   

答案 1 :(得分:0)

或者,如果您只想提示输入凭据,则:

Invoke-RestMethod -Method Get -Uri $uri -Credential (Get-Credential)

括号将Get-Credential cmdlet作为表达式运行,该cmdlet输出一个PSCredential对象,该对象用作-Credential参数的参数。