Powershell Invoke-Restmethod不能将生成的Authtoken用作变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Powershell Invoke-Restmethod不能将生成的Authtoken用作变量相关的知识,希望对你有一定的参考价值。
i´am试图通过Powershell访问RESTAPI。在登录过程中,将生成一个Authtoken,以后的任何命令都需要它,并且必须将它放入标头中。到目前为止,没有什么特别的。当然,我想将生成的Authtoken放入变量中,以便于处理。但是我做不到...这是我在尝试的方法:登录并获取Authtoken
$payload = @{"login"="username";"password"="password"}
$AuthToken = Invoke-RestMethod -Method Post -ContentType application/json -Body (ConvertTo-Json $payload) -Uri "https://path/to/api/login"
因为API仅接受特殊形式的授权,所以我必须对其进行一些编辑
$AuthToken = $AuthToken.Replace("auth_token=",'"auth_token"="')
$AuthToken = $AuthToken.Insert(73,‚"‘)
之前的Authtoken
@{auth_token=rShln/Yc2cepDtzbNFntdZue:9c3ce025e5485b14090ca25500f15fa2}
以及治疗后
@{"auth_token"="St6tecwEseAQegkfhACXUwaj:d7e3e2095ba31073e3fbc043c4563d28"}
如果我手动将Authtoken插入Rest方法中,则呼叫看起来是这样的:
Invoke-RestMethod -Method Get -ContentType application/json -Headers @{"auth_token"="JsRaTBRlElpq1jLLX5z3TXUy:91d0e1eee1943f6cd6dbaa1d0b9ba9d0"} -Uri "https://path/to/api/something"
您可能会猜到,这很好用!如果现在尝试使用变量中的Authtoken,则我的Rest Call看起来像这样:
Invoke-RestMethod -Method Get -ContentType application/json -Headers $Authtoken -Uri "https://path/to/api/something"
Powershell给我以下错误
Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert the "@{"auth_token"="St6tecwEseAQegkfhACXUwaj:d7e3e2095ba31073e3fbc043c4563d28"}" value of type "System.String" to type
"System.Collections.IDictionary".
At C:UsersUserDesktopxxx.ps1:6 char:70
+ ... -Method Get -ContentType application/json -Headers $AuthToken -Uri "h ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
我不知道为什么我会收到此错误,并且非常感谢,有人可以帮我解决这个问题!
所以现在看起来$AuthToken
是一个字符串。字符串的格式就像您希望的哈希表那样,但是我认为它实际上不是哈希表。您可以通过在字符串上使用Invoke-Expression
来解决此问题,并将其转换为实际的哈希表。类似于:
$AuthToken = Invoke-Expression $AuthToken
Invoke-RestMethod -Method Get -ContentType application/json -Headers $Authtoken -Uri "https://path/to/api/something"
标题应该在System.Collections.IDictionary方法中(检查:https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.system-collections-idictionary-add?view=netframework-4.8)
示例:正在使用centeron api标头变量应为:$ headers = @ {“ centreon-auth-token” =“ $ Key”}密钥仅包含令牌,例如:NWU5ZDY5ODFiNWI2YTYuMzAzNjM3NDI =
以上是关于Powershell Invoke-Restmethod不能将生成的Authtoken用作变量的主要内容,如果未能解决你的问题,请参考以下文章
powershell PowerShell:启动PowerShell作为其他用户提升
powershell [提示输入powershell] #powershell #input #prompt