Bryan Arreola
Bryan Arreola

Reputation: 307

Access Array of object inside a PSCustomObject Powershell

I have this PSCustomObject which I'm trying to format into a table and export it to an .csv file, when the .csv file is built, the output in the cell is System.Object[].

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

$tableFindings outputs

{
    "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
        }
    ]
}

I'm having a hard time trying to figure out how to access the array of objects, assets is one of the arrays, but inside there is dnsName that is also an array. Any suggestions?

Upvotes: 2

Views: 1927

Answers (1)

mklement0
mklement0

Reputation: 439682

If all you're interested in is a flat array of the dnsName values, across all objects stored in the assets array, use member-access enumeration:

$item.assets.dnsName

To incorporate this into [pscustomobject] instances that you can send to Export-Csv:

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

Note the use of -join ' ' in order to convert an array of values to a single string, with the elements joined with spaces, given that arrays don't stringify meaningfully with Export-Csv

Note how the foreach statement is used as an expression, which means that PowerShell automatically collects the [pscustomobject] instances output in each iteration in variable $tableFindings.

Upvotes: 4

Related Questions