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?
Asked
Active
Viewed 9,426 times
2 Answers
5
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
- 113,841
0
Adding on to the answer above, you can do something like
$obj2 = $objtest | select NotFoo, NotBar
To permanently remove the original members
powerkor
- 1