powershell - 对象是空的吗?
问题描述
我正在使用 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
我不确定queries
andresults
对象是否为空,或者我需要其他方式来阅读它们。
解决方案
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-Json
JSON 。请注意,后者的默认序列化深度限制为 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
...
推荐阅读
- javascript - jQuery v3.0 不再支持 unbind 了,真的吗?
- c# - 如何检查游戏对象是否处于活动状态
- c# - 脚本,附加到 2 个场景,不起作用
- javascript - 即使焦点集中,使用 Enter/Space 键单击元素也不起作用(可访问性)
- rdf - owlready2 rdfs:subClassOf 推理不起作用
- c - 在while循环中多次调用函数
- mysql - 如何按 id 删除 mySQL JSON 列元素,而不是按索引 num
- html - 如何将网格与引导程序一起用于表单(v3)?
- c++ - C++ 部分运行程序,直到我切换到 DOS shell
- python - 将带有光标的小部件移动到另一个布局