首页 > 解决方案 > 对象是空的吗?

问题描述

我正在使用 Azure API > https://docs.microsoft.com/en-us/rest/api/azure/devops/git/pull%20request%20query/get?view=azure-devops-rest-5.1

我正在使用这段代码:

$body = @"
{
    "queries": [{
        "items": [
            "59c1c31397b266116ff6d735e5638ef5d1b598a0"
        ],
        "type": "commit"
    }]
}
"@ 

$x = Invoke-RestMethod -Uri $someLink -Headers @{Authorization = $pat } -Body $body -Method Post -ContentType 'application/json'
Write-Host $x
Write-Host $x | ConvertFrom-Json
Write-Host $x.results | ConvertFrom-Json

出于安全原因,我已删除该链接。

当我运行代码时,我在控制台中得到以下信息:

2020-01-20T16:17:55.8600905Z @{queries=System.Object[]; 结果=System.Object[]}

2020-01-20T16:17:55.8637026Z @{queries=System.Object[]; 结果=System.Object[]}

2020-01-20T16:17:55.8674193Z

我不确定queriesandresults对象是否为空,或者我需要其他方式来阅读它们。

标签: powershell

解决方案


  • Write-Host写入主机(通常是控制台/终端),绕过 PowerShell 的成功输出流,这就是为什么这样的命令Write-Host $x | ConvertFrom-Json是没有意义的,因为ConvertFrom-Json不会收到任何输入

  • Write-Host将非字符串输入对象的简单.ToString()字符串化写入主机,这意味着您不会获得 PowerShell 丰富、人性化的输出格式,默认情况下最终打印到主机时Write-Output会导致隐式输出或(很少需要)显式调用,由于输出既没有被捕获在变量中也没有被重定向)。>

  • Invoke-RestMethod 自动将其接收到的 JSON 输出解析为 PowerShell自定义对象([pscustomobject]实例,因此也没有概念上的理由将其属性值传递给ConvertFrom-Json- 除非 API 真正返回嵌套的 JSON 文本作为它返回的 JSON 中的字符串值


如果您想直观地检查结果,只需直接输出即可:

$x  # output visualization of the whole object
$x.results  # just the .results property

以上输出到成功输出流,这意味着您的代码的外部调用者将接收这些值作为代码输出的一部分。

如果生成的类似表格或类似列表的格式(取决于属性的数量)不能告诉您足够多的信息,您可以通过管道将对象转换ConvertTo-JsonJSON 。请注意,后者的默认序列化深度限制为 2,因此您可能必须传递更高的-Depth值才能完整查看对象 - 请参阅这篇文章

$x | ConvertTo-Json  # use -Depth <n>, if needed.
$x.results | ConvertTo-Json

如果您真的只想将值打印为 user 的信息,而不成为输出的一部分,请使用Out-Host而不是Write-Host,因为Out-Host 确实应用了丰富的格式:

$x | Out-Host # print visualization of the whole object directly to the host
$x.results | Out-Host  # just the .results property

# Ditto via ConvertTo-Json
$x | ConvertTo-Json | Out-Host
...

推荐阅读