【问题标题】:How to format JSON Output into a Grid for Format-Table in PowerShell如何将 JSON 输出格式化为 PowerShell 中的 Format-Table 网格
【发布时间】:2021-11-28 15:14:50
【问题描述】:

下面的代码是显示我想要的数据,但它没有很好地对齐。 如何使用数据网格或格式表来对齐数据?

$response = Invoke-RestMethod @params
foreach ( $row in $response )
{
    Write-host "id=$($row.uuid) uuid=$($row.uuid) Subject=$($row.subject) " 
}

现在的示例输出:

id=new-template_1 uuid=new-template_1 Subject=Welcome! 
id=new-template_3 uuid=new-template_3 Subject=Welcome!

期望:

    id              uuid             subject 
new_template_1    new_template_1    Welcome! 
new_template_3    new_template_3    Welcome!  

【问题讨论】:

  • 将您的 write-host 更改为 [pscustomobject]@{ 'id'=$row.uuid ...}
  • Invoke-RestMethod @params |Select-Object @{Name='id';Expression='uuid'},uuid,Subject

标签: json powershell invoke-restmethod


【解决方案1】:

如果您只想从Invoke-RestMethod 输出的对象中“修剪”一组属性,请使用Select-Object

$response = Invoke-RestMethod @params
$trimmedResponse = $response |Select-Object @{Name='id';Expression='uuid'},uuid,subject

# This will now default to table view formatting
$trimmedResponse

# But you can also explicitly pipe to `Format-Table` 
$trimmedResponse |Format-Table

# ... allowing you greater control over the formatting behavior
$trimmedResponse |Sort-Object Subject |Format-Table -GroupBy Subject

传递给Select-Object (@{Name='id';Expression='uuid'}) 的第一个参数称为calculated property - 在这种情况下,它定义了一个名为id 的新属性,其值为输入对象的uuid 属性.

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2020-06-15
    • 1970-01-01
    • 2016-01-26
    • 2022-07-20
    • 2016-09-24
    相关资源
    最近更新 更多