gpt4 book ai didi

Powershell Invoke-Restmethod 不能使用生成身份验证 token 作为变量

转载 作者:行者123 更新时间:2023-12-02 22:24:30 26 4
gpt4 key购买 nike

我正在尝试通过 Powershell 访问 RESTAPI。
在登录过程中,会生成一个 Authtoken,任何后续命令都需要它,并且必须将其放入 header 中。到目前为止没有什么特别的。
当然,我想将生成的 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 插入 Restmethod 调用看起来是这样的:
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:\Users\User\Desktop\xxx.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是一个字符串。该字符串的格式与您期望的 Hashtable 一样,但我认为它实际上不是一个哈希表。您可以使用 Invoke-Expression 来解决此问题。在字符串上,这将为您将其转换为实际的哈希表。就像是:

$AuthToken = Invoke-Expression $AuthToken
Invoke-RestMethod -Method Get -ContentType application/json -Headers $Authtoken -Uri "https://path/to/api/something"

关于Powershell Invoke-Restmethod 不能使用生成身份验证 token 作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35708990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com