Add-Member enhancements in PowerShell 3.0
PowerShell 3.0 offers new ways to add Note properties to objects. In PowerShell 2.0, a typical command to do that would look like:
PS> New-Object -TypeName PSObject |
Add-Member -MemberType NoteProperty -Name One -Value 1 -PassThru
One
---
1
And when adding multiple note properties:
PS> New-Object -TypeName PSObject |
Add-Member -MemberType NoteProperty -Name One -Value 1 -PassThru |
Add-Member -MemberType NoteProperty -Name Two -Value 2 -PassThru |
Add-Member -MemberType NoteProperty -Name Three -Value 3 -PassThru
One Two Three
--- --- -----
1 2 3
As you can see the syntax was very long and each time you created a NoteProperty you had to specify that. In Powershell 3.0 Add-Member have to new parameters: NotePropertyName and NotePropertyValue. Now you can easily add a NoteProperty without having to specify the member type and without having to specify parameter names, we take advantage of their positional value.
PS> New-Object -TypeName PSObject | Add-Member One 1
One
---
1
To add multiple NoteProperty we can now use a hashtable:
PS> New-Object -TypeName PSObject | Add-Member @{One=1; Two=2; Three=3} -PassThru
One Three Two
--- ----- ---
1 3 2
Notice that the object we got back didn't preserve the order of properties defined in the hashtable. Order in a dictionary is defined the moment you create it and the regular hashtable syntax @{} is an unordered dictionary. To make sure properties are listed in the order we defined them, we use an ordered hashtable.
PS> $pso = New-Object -TypeName PSObject
PS> $pso | Add-Member ([ordered]@{One=1; Two=2; Three=3}) -PassThru
One Two Three
--- --- -----
1 2 3
Finally, there's another interesting new parameter: TypeName. We can use it to specify a name for the resultant object type. This is very useful when you use format files to define the default display of your objects. Previously we had to add the type name to the object's PSTypeNames list, now it is even easier.
PS> $pso = New-Object -TypeName PSObject
PS> $pso | Add-Member ([ordered]@{One=1; Two=2; Three=3}) -TypeName MyType.MyObject
PS> $pso | Get-Member
TypeName: MyType.MyObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
One NoteProperty System.Int32 One=1
Three NoteProperty System.Int32 Three=3
Two NoteProperty System.Int32 Two=2