Renaming Object Columns

by Oct 9, 2012

In some of our previous tips, we showed how you can turn comma-separated data returned from different console tools into rich PowerShell objects. You also learned how you can access the columns in a culture-neutral way. Today, we'd like to present a solid solution that also allows you to reassign new column names, making the data truly culture-neutral across different platforms.

Here is an example that uses raw data provided from tasklist.exe and then turns it into objects with self-defined column headers. The variable $columns holds the original column headers. The variable $columnNames lists the alternative names that you want to use instead:

$data = @(tasklist /V /FO CSV | ConvertFrom-Csv)
$columns = $data[0].PSObject.Properties | Where-Object { $_.MemberType -eq 'NoteProperty' } | Select-Object -ExpandProperty Name
$columnNames = 'Name', 'ID', 'Session', 'SessionID', 'Memory', 'Status', 'Owner', 'CPU', 'Title'
$customProperties = $columns | ForEach-Object {$i=0}{ @{Name = $columnNames[$i] Expression=[ScriptBlock]::Create(('$_.''{0}''' -f $columns[$i]))} $i++ }
$data | Select-Object -Property $customProperties

As a result, you get extensive information about all running processes (that goes beyond what Get-Process can do), and object properties are no longer localized but instead use the names you provided.

Here is another example to illustrate that only few things need to be adjusted for other commands (provided they return data as comma-separated values):

$data = @(schtasks /FO CSV | ConvertFrom-Csv)
$columnNames = 'Name', 'NextCall', 'Status'
$columns = $data[0].PSObject.Properties | Where-Object { $_.MemberType -eq 'NoteProperty' } | Select-Object -ExpandProperty Name
$customProperties = $columns | ForEach-Object {$i=0}{ @{Name = $columnNames[$i] Expression=[ScriptBlock]::Create(('$_.''{0}''' -f $columns[$i]))} $i++ }
$data | Select-Object -Property $customProperties

Twitter This Tip! ReTweet this Tip!