访问 PSCustomObject Powershell 中的对象数组

Access Array of object inside a PSCustomObject Powershell

我有这个 PSCustomObject,我试图将其格式化为 table 并将其导出到 .csv 文件,当构建 .csv 文件时,单元格中的输出是 System.Object[].

$tableFindings = @() 
foreach ($item in $findings.results) { 
    $tabledata = [ordered]@{
        dnsName = $item.assets| ForEach-Object dsnName
    }
    $tableFindings += New-Object psobject -Property $tabledata
}

$tableFindings 输出

{
    "temporary_id": "xxxxxxxxxxxxxxxxxx",
    "affects_rating": true,
    "assets": [
        {
            "asset": "xxxxxxxx",
            "identifier": null,
            "category": "critical",
            "dnsName": [
                "xxxxxxxxxxxxxxx",
                "xxxxxxxxxxxxxxx"
            ],
            "is_ip": false
        },
        {
            "asset": "xxxxxxxx",
            "identifier": null,
            "category": "critical",
            "dnsName": [
                "xxxxxxxxxxxxxxx",
                "xxxxxxxxxxxxxxx"
            ],
            "is_ip": false
        }
    ]
}

我很难弄清楚如何访问对象数组,assets 是其中一个数组,但里面有 dnsName 也是一个数组。 有什么建议吗?

如果您只对 平面数组dnsName 值感兴趣,所有对象 存储在assets 数组,使用 member-access enumeration:

$item.assets.dnsName

要将其合并到 [pscustomobject] 个实例中,您可以发送至 Export-Csv:

$tableFindings = foreach ($item in $findings.results) {
  [pscustomobject] @{
    # ... add other properties as needed.
    dnsName = $item.assets.dnsName
  }
}

请注意 foreach 语句如何用作 表达式 ,这意味着 PowerShell 自动收集变量 [pscustomobject] 每次迭代中的实例输出 $tableFindings.