Shell – Powershell Custom Properties – Change Property name

powershellpowershell-4.0

I have a custom object, and I would like to change the property name of one of the existing properties. Is that possible? I know I could create a new property with the new name, copy the values from the old property and then select only the properties I want (new property, but exclude the old one), but is there a simpler way?

Best Answer

With object properties "Name" is a read-only property, and so cannot be changed during runtime.

$objTest = New-Object -TypeName PSObject -Property @{ Foo = 42; Bar = 99 }
$objTest.PSObject.Properties["Foo"].Name  # Output: Foo.
$objTest.PSObject.Properties["Foo"].Name = "NotFoo"  # Output: 'Name' is a ReadOnly property.

An alternate to creating a new property and copying values may be to create a new "AliasProperty", which is a new property (with its own name) that is simply linked to an existing property.

eg.:

PS Y:\> $objTest | Add-Member -MemberType AliasProperty -Name Notfoo -Value Foo
PS Y:\> $objtest

Bar Foo Notfoo
--- --- ------
 99  42     42

PS Y:\> $objtest.Foo = 123
PS Y:\> $objtest

Bar Foo Notfoo
--- --- ------
 99 123    123
Related Question