Bulk Renaming Object Properties

by May 15, 2014

Occasionally, it may become necessary to bulk rename object properties to create better reports. For example, if you retrieve process objects, you may need to create a report with column headers that are different from the original object properties.

Here is a filter called Rename-Property that can rename any property for you. In the example, a process list is generated, and some properties are renamed:

filter Rename-Property ([Hashtable]$PropertyMapping)
{
    Foreach ($key in $PropertyMapping.Keys)
    {
        $_ = $_ | Add-Member -MemberType AliasProperty -Name $PropertyMapping.$key -Value $key  -PassThru
    }
    $_
}

$newProps = @{
  Company = 'Manufacturer'
  Description = 'Purpose'
  MainWindowTitle = 'TitlebarText'
}

# get raw data
Get-Process | 
    # add alias properties as specified in $newProps
    Rename-Property $newProps |
    # select the properties you want to display
    # can be original properties and/or newly added alias properties
    Select-Object -Property Name, Manufacturer, Purpose, TitlebarText 

Rename-Property automatically adds all the properties specified in $newProps. The resulting objects have new properties named “Manufacturer”, “Purpose”, and “TitlebarText”. You can then use Select-Object to select the properties you want in your report. You can choose from the existing original properties and the newly added alias properties.

So actually, the properties are not renamed (which is technically impossible). Rather, the filter adds alias properties with a new name that point back to the original properties.

Twitter This Tip! ReTweet this Tip!