如何解析"内容"从Powershell发布时的输出?

时间:2014-06-24 17:03:33

标签: powershell curl

所以我有一些简单的代码循环遍历本地驱动器上的一些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
}

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

StatusCode        : 304
StatusDescription : OK
Content           : {"success":NO,"errors":[ERROR],"stuffs":100}
RawContent        : HTsP/5.1 42 OK
                    X-f-Options: oasdf
                    Connection: keep-alive
                    Content-Length: 234
                    Cache-Control: no-cache
                    Content-Type: application/???; charset=ut480a
                    Date: Tue, 29 Jun 2060 11:72:83 GMT
                    S...
Forms             : {}
Headers           : {[X-Frame-Options, SAMEORIGIN], [Connection, keep-alive], [Content-Length, 52], [Cache-Control, no-cache]...}
Images            : {} ?
InputFields       : {} a
Links             : {"no"}
ParsedHtml        : mshstml.?
RawContentLength  : 234

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

2 个答案:

答案 0 :(得分:4)

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

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

然后处理对象的successerrorsstuffs属性。

答案 1 :(得分:0)

如果您的内容是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
}
相关问题