PowerShell - modify a property in an array
We have a PowerShell dataset where we want to modify the values of a property but we don’t want to add a new property.
Imagine we want to convert the data like this, modifying one property so all the values are upper case but everything else is unchanged:
1Name Age MyProperty Name Age MyProperty
2---- --- ---------- ---- --- -------------------
3Hugh 37 abc123 ----> Hugh 37 ABC123
4Pugh 24 ABCdef ----> Pugh 24 ABCDEF
5Barney 21 GHIjkL ----> Barney 21 GHIJKL
Let’s define this example data to work through a solution:
1$dataset=@(
2 [PSCustomObject]@{ Name = 'Hugh'; Age =37; MyProperty = 'abc123' }, `
3 [PSCustomObject]@{ Name = 'Pugh'; Age =24; MyProperty = 'ABCdef' }, `
4 [PSCustomObject]@{ Name = 'Barney'; Age =21; MyProperty = 'GHIjkL' } `
5)
Our initial dataset therefore looks like this:
1$dataset
2
3Name Age MyProperty
4---- --- ----------
5Hugh 37 abc123
6Pugh 24 ABCdef
7Barney 21 GHIjkL
We can add a new property with MyProperty
converted into upper-case quite easily using this PowerShell. We’re selecting all the properties with *
and then
adding a new property with the upper-cased value of each item.
1$dataset | Select-Object *, @{Name="MyUpperCaseProperty";Expression={$_.MyProperty.toUpper()}}
2
3Name Age MyProperty MyUpperCaseProperty
4---- --- ---------- -------------------
5Hugh 37 abc123 ABC123
6Pugh 24 ABCdef ABCDEF
7Barney 21 GHIjkL GHIJKL
But we want to replace the values in MyProperty
, not add a new one. If we try to overwrite it by calling our replacement property MyProperty
we get an error.
1$dataset | Select-object *, @{Name="MyProperty";Expression={$_.MyProperty.toUpper()}}
2Select-Object: The property cannot be processed because the property "MyProperty" already exists.
The solution is to exclude the original MyProperty
using the ExcludeProperty
parameter of Select-Object
like this:
1$dataset | Select-Object *, @{Name="MyProperty";Expression={$_.MyProperty.toUpper()}} -ExcludeProperty MyProperty
2
3Name Age MyProperty
4---- --- ----------
5Hugh 37 ABC123
6Pugh 24 ABCDEF
7Barney 21 GHIJKL
And remember, we can also put this result back into our $dataset
variable:
1$dataset= $dataset | Select-Object *, @{Name="MyProperty";Expression={$_.MyProperty.toUpper()}} -ExcludeProperty MyProperty