2

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?

Bryan Arreola
  • 197
  • 1
  • 6
  • 22
  • 1
    You are trying to force a 3d array into a 2d array and it's going to fail. You need to either output to a format that supports nested arrays (such as JSON or XML), or flatten your array somehow (iterate nested arrays and join the results, or create an additional record for each iteration). How do you want the output to appear? – TheMadTechnician Jun 15 '21 at 21:59
  • Well, JSON is morea manageable in my opinion – Bryan Arreola Jun 15 '21 at 22:03
  • If you like JSON, can you just export it as that and skip the CSV? Or is somebody requiring you to convert this to CSV? – TheMadTechnician Jun 15 '21 at 23:40
  • JSON has it's times where it has trouble converting it back to it's original data type such as `timespan`. – Abraham Zinala Jun 16 '21 at 00:10
  • It is a requirement to export it to CSV – Bryan Arreola Jun 16 '21 at 20:57

1 Answers1

4

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775