【发布时间】:2020-07-16 00:47:52
【问题描述】:
我正在尝试创建一个新对象,我也可以传递用户名/密码,以便在与我正在使用的其他 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
只是为了验证我的代码,和微软的例子基本一样:
$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 命令?
【问题讨论】:
-
如错误消息所述。没有接受两个
String(docs) 类型参数的“PSCredential”构造函数。唯一接受 2 个参数的构造函数需要String和SecureString。所以你的基本问题是:如何将字符串转换为 SecureString。 -
感谢您,@TobyU 也提到了这一点,并且可以看到他包含了 Microsoft 在其页面上使用的相同转换(doh!),我现在正在使用此方法将字符串转换为 SecureString,但是将其传递给 Invoke-RestMethod 命令时,我仍然碰壁。
-
当您明确声明参数名称时会发生什么,即
-Credential $Credential?
标签: powershell