Powershell-从PSObject的多行(或多个JSON数组项)中的字段获取非空值的数组?

时间:2019-01-29 20:48:51

标签: powershell powershell-v4.0

我有一些像这样的JSON(来自PSObject):

[
    {
        "cf_workflow_1":  1212,
        "cf_workflow_2":  null,
        "cf_workflow_3":  null
    },
    {
        "cf_workflow_1":  null,
        "cf_workflow_2":  9797,
        "cf_workflow_3":  null
    },
    {
        "cf_workflow_1":  6262,
        "cf_workflow_2":  null,
        "cf_workflow_3":  null
    }
]

我想提取一个简单的数组:

(1212,9797,6262)

我该怎么做?

以下是一些示例代码可以使用:

$tickets = @"
        [
            {
                "cf_workflow_1":  1212,
                "cf_workflow_2":  null,
                "cf_workflow_3":  null
            },
            {
                "cf_workflow_1":  null,
                "cf_workflow_2":  9797,
                "cf_workflow_3":  null
            },
            {
                "cf_workflow_1":  6262,
                "cf_workflow_2":  null,
                "cf_workflow_3":  null
            }
        ]
"@

$ticketsObject = $tickets | ConvertFrom-Json 

#Show the ticket data
$ticketsObject | Format-Table -AutoSize

#Create an array to hold all the non-null workflow numbers
#It should eventually contain the value (1212,9797,6262)
$workflowNumbers = @()

#Not sure what to do here to return only the non-null workflow numbers as an array?
$workflowNumbers = $ticketsObject | foreach{$_}

1 个答案:

答案 0 :(得分:1)

这有效:

$ticketsObject | 
  ForEach-Object {$_.Psobject.properties | 
                 where-Object {$_.Name -like 'cf*' -and $_.Value } | select -expand Value}

想法是查看每个对象的属性(仅cf *的属性)和仅具有值的属性,然后仅获取值。