Home > database >  Flattening an array in powershell
Flattening an array in powershell

Time:11-25

I have some code that pulls from an API into a variable called $table. I can export this variable to a csv with no issues, except the last field in the table ($table.userdefinedfields) exports as a SystemObject[].

What I would like is a 3 column table consisting of the 1st and 3rd fields of $table and the 29th field of the SystemObject[].

I am not too well versed in powershell, but this must be possible.

Any ideas?

CodePudding user response:

Use Select-Object with a calculated property:

$table | 
  Select-Object -ExcludeProperty userdefinedfields -Property *, @{
    Name = 'Field29' # change as needed
    Expression = { $_.userdefinedfields[28] }
  } # | Export-Csv ...

The above uses all original properties (*), except the userdefinedfields property, and adds a calculated property with self-chosen name Field29 that contains the 29th element ([28]) of the array stored in each input object's .userdefinedfields property.

Since you only want a subset of the original properties, replace * with the property names of interest, i.e the names of the 1st and 3rd properties (e.g., Foo, Bar); you can then omit the -ExcludeProperty parameter.

CodePudding user response:

Thanks for the help....All good now

  • Related