Renaming Object Properties

by May 8, 2009

You can use Select-Object to rename existing object properties. For example, you would like to rename e a directory listing "Name" property to "FileName". Here is how you do it:

dir | Select-Object @{Name='FileName'={$_.Name}}, Length

Select-Object accepts hash tables and expects to find a Name and an Expression field. The Name field determines the new object property name, and the expression field really is a script block that creates the property value. $_ represents the actual object so you can really create any new object property. The next line adds a property called KB which contains the file size in kilobytes:

dir | Select-Object @{Name='KB'={'{0:0.0} KB' -f `
($_.Length/1KB)}}, Name, Length