【问题标题】:In Powershell, how do I pull specific text from an object that was returned by an API response?在 Powershell 中,如何从 API 响应返回的对象中提取特定文本?
【发布时间】:2020-06-15 00:41:53
【问题描述】:

这里是 Powershell 的新手,因此感谢您提供任何建议!我正在发布到该网站的 API(我在下面的代码中将其代号为 authenticate.com)以在响应中接收身份验证令牌作为 cookie。下一个目标是获取 cookie 并使用它来验证不同的 API。如何捕获第一个 API 返回的 auth-token 并将其保存到变量中?

我的代码:

$Url = 'https://authenticate.com/apikeylogin'
$auth = @{
     keyPublic= '********************'
     keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$response | Get-Member
$response.RawContent

原始文本中的响应:

HTTP/1.1 200 OK
auth-token: ******************
[Below this is are a dozen more lines of raw data]

重申一下问题,我如何获得上述“auth-token”的值并将其存储到变量中?

【问题讨论】:

  • 根据我的阅读,通常您使用Invoke-RestMethod 而不是面向网页的Invoke-WebRequest cmdlet。如果返回 JSON,I-RM 东西会自动将返回的数据转换为结构化对象。从...中获取信息相当容易 [grin]
  • 要查看您的对象有哪些成员和数据,您可以将其通过管道传送到Select-Object,如下所示:$response | Select-Object -Property *
  • @Lee-Daily 我最初尝试过 Invoke-RestMethod。问题是它隐藏了太多的响应,我看不到我需要的身份验证令牌!谢谢
  • @Theo 我在发布我的问题之前看到了这个!我认为这与我的问题相似并且有所帮助,但我无法按照它的逻辑取得成功。尽管我试图解决这个问题,但我仍在使用它作为参考!谢谢!

标签: powershell api https


【解决方案1】:

您可以使用 Select-String(类似于 powershell 中的 grep)找出包含 auth-token 的行并获取 auth-token 值。

$response = "HTTP/1.1 200 OK `
auth-token: ABCDEFGHIJKLMNOP `
[Below this is are a dozen more lines of raw data]"

$authTokenline =
 $response.Split("`n") | Select-String -Pattern "^auth-token:.*$" 
$authToken = $authTokenline.ToString().Split(":")[1]
ABCDEFGHIJKLMNOP

【讨论】:

  • 感谢您的回答!我试过这个,我得到了错误:你不能在空值表达式上调用方法。 CategoryInfo:InvalidOperation (:) [],RuntimeException,FullyQualifiedErrorId:InvokeMethodOnNull。我目前正在解决这个错误!
【解决方案2】:

好的,我已经使用 .Substring() 解决了这个问题

$auth = @{
     keyPublic= '********************'
     keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$raw = $response.RawContent
$string = $raw | Out-String
$auth_token = $string.Substring(35, 90)

我从 API 请求的访问令牌始终具有相同的长度,因此我使用 substring 方法准确确定字符串中的哪些字符是我需要的,然后将它们存储在变量“auth-token”中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多