I'm outputting a couple of objects from a data table to a .csv file and wanted to change the object names.
This works fine:
$dataset.tables[0] | select-object System.ItemName, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
However I'd like to change System.ItemName to SKU and have tried the following:
$dataset.tables[0] | select-object @{N='SKU';E={$_.System.ItemName}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
This gives the right column heading but blank rows. So tried this which give rows but they all say SYSTEM.ITEMNAME:
$dataset.tables[0] | select-object @{N='SKU';E={$dataset.tables[0].Columns['SYSTEM.ITEMNAME']}}, System.ItemPathDisplay | Export-Csv -Path D:\SEARCH_RESULT.csv -NoTypeInformation
Clearly I'm not referencing the object correctly. Any help greatly appreciated.
CodePudding user response:
Change $_.System.ItemName
to $_.'System.ItemName'
Your property name is System.ItemName
, and if a property name itself contains .
, it must be quoted - otherwise, PowerShell interprets it as a nested property access
That is, $_.System.ItemName
looks for a property on object $_
named System
first, and then for an ItemName
property on the first property's value; PowerShell defaults to $null
when accessing non-existent properties.
Contrast this with the use of System.ItemName
as an argument passed to the (positionally implied) -Property
parameter of the Select-Object
cmdlet, where the argument is always interpreted as a single property name (whether you quote it or not).
In other words: Select-Object
doesn't directly support nested property access, but you can do it via a calculated property, as in your approach.