Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell change output object name from datatable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

>Solution :

Change $_.System.ItemName to $_.'System.ItemName'

Your property name is System.ItemName, and if a property name itself contains ., the property name 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading