【问题标题】:How to parse "Content" output when POSTing from Powershell?从 Powershell 发布时如何解析“内容”输出?
【发布时间】:2014-08-15 01:20:53
【问题描述】:

我有这段代码,它遍历我本地驱动器上的一些 JSON 文件并将它们发布到带有 cURL 的 URL:

$negativeTests = Get-ChildItem "C:\Users\ME\Documents\folder\folder\"
#Write-Host $negativeTests;
for ($i = 0; $i -lt $negativeTests.Count; $i++) {
    $tempFile = Get-Content $negativeTests[$i].PSPath
    Invoke-WebRequest -Uri https://myWebsite.com/ext/ext/ext -Method POST -Body $tempFile
}

此代码在运行时以以下格式从服务器提供此输出:

状态码:304

状态描述:正常

内容:{"success": NO, "errors": [ERROR], "stuffs": 100}

原始内容:HTsP/5.1 42 OK

X-f-选项:oasdf

连接:保持活动

内容长度:234

缓存控制:无缓存

Content-Type: application/???;字符集=ut480a

日期:格林威治标准时间 2060 年 6 月 29 日星期二 11:72:83

S...

表格:{}

标题:{[X-Frame-Options, SAMEORIGIN], [Connection, keep-alive], [Content-Length, 52], [Cache-Control, no-cache]...}

图片:{} ?

输入字段:{} a

链接:{"no"}

ParsedHtml : mshstml.?

原始内容长度:234

如何获取和解析此输出的Content: {"success":NO,"errors":[ERROR],"stuffs":100} 部分?理想情况下,我会检查文件是否上传成功。

【问题讨论】:

    标签: json powershell parsing curl post


    【解决方案1】:

    Content 属性的值看起来像 JSON 字符串,因此您应该能够将其转换为 PowerShell 对象,如下所示:

    Invoke-WebRequest ... | select -Expand Content | ConvertFrom-Json
    

    然后处理对象的successerrorsstuffs属性。

    【讨论】:

      【解决方案2】:

      如果你的内容是 JSON 并且你有 Powershell 4.0,Invoke-RestMethod 可能更容易使用 Invoke-WebRequest。它将自动从内容中解压缩 JSON 响应并对其进行解析。它还有一个参数可以直接从输入文件中读取正文,InFile

      $negativeTests = Get-ChildItem "C:\Users\ME\Documents\folder\folder\"
      #Write-Host $negativeTests;
      for ($i = 0; $i -lt $negativeTests.Count; $i++) {
          Invoke-WebRequest -Uri https://myWebsite.com/ext/ext/ext -Method POST -InFile $negativeTests[$i].FullName
      }
      

      【讨论】:

        【解决方案3】:

        如果您想查看完整内容,只需在 Powershell 中的 CURL 命令末尾添加 | Select -ExpandProperty Content,如下所示:

        curl -v -Method Post -Uri 'https://myapi.com/myMethod' -headers @{"Content-Type"= "application/json"} -Body '{"myToken": "123"}' | Select -ExpandProperty Content
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-01-03
          • 1970-01-01
          • 1970-01-01
          • 2019-07-09
          • 1970-01-01
          • 2022-11-15
          • 1970-01-01
          相关资源
          最近更新 更多