'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?
Solution 1:[1]
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 you can send to Export-Csv:
$tableFindings = foreach ($item in $findings.results) {
[pscustomobject] @{
# ... add other properties as needed.
dnsName = $item.assets.dnsName
}
}
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
