Powershell Custom Properties - Change Property name

3

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?

G Raybin

Posted 2016-10-05T15:28:58.367

Reputation: 33

Answers

3

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

Ƭᴇcʜιᴇ007

Posted 2016-10-05T15:28:58.367

Reputation: 103 763

0

Adding on to the answer above, you can do something like

$obj2 = $objtest | select NotFoo, NotBar

To permanently remove the original members

powerkor

Posted 2016-10-05T15:28:58.367

Reputation: 1