如何使Invoke-RestMethod按原样打印响应正文

Nit*_*kin 6 rest json powershell-5.0

我正在尝试使用powershell cmdlet Invoke-RestMethod将json端点打印到控制台.

该命令成功执行,但最终结果是包含所有json的1级字段的终端表.

我正在运行这样的cmdlet:

Invoke-RestMethod -Uri <some url here> -Method GET -ContentType "application/json"
Run Code Online (Sandbox Code Playgroud)

得到这样的东西:

sections _links
-------- ------
         {@{rel=parent; href=https://us9.api.mailchimp.com/3.0/templates/138...
Run Code Online (Sandbox Code Playgroud)

如何在不格式化的情况下将原始响应打印到终端?

4c7*_*b41 8

首先,将-Method-ContentType您所提供的默认值,你可以丢弃这些.为了得到json,把它扔回json.

Invoke-RestMethod -Uri "http://example.com/" | ConvertTo-Json -Depth 10
Run Code Online (Sandbox Code Playgroud)

我不知道你为什么要回到json,但好吧,你走了.

  • 请注意,`-Depth` 参数默认为 2,并且未正确处理任何更低的 JSON 字段(在我的情况下,字符串数组条目都连接到同一个条目中)。发生这种情况时,此 cmdlet 不会发出警告,因此,如果您使用 ConvertTo-Json,请确保为您的数据将深度设置为适当大的值。 (6认同)

NH.*_*NH. 6

另一个答案适用于 JSON 响应,但 -UseBasicParsing 开关适用于任何响应类型:

(Invoke-WebRequest -UseBasicParsing -Uri 'http://example.com').Content
Run Code Online (Sandbox Code Playgroud)

只会给你响应内容(在 example.com 案例中,原始 html,或在你的用例中,原始 JSON)。

  • 请注意,自 6.0.0 起已弃用:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-6 (2认同)