You are very close. The problem is that you're not creating the object correctly. You need to specify the -Property
parameter before you specify a hashtable of properties. Without it, you just create a hashtable. This works:
$props = @{"Mary"=1;"Jane"=2;"Frank"=3;"John"=5;"Brenda"=6}
$obj = New-Object -TypeName PSObject -Property $props
$obj | Add-Member PropertySet "Male" @("Frank","John")
$obj | Add-Member PropertySet "Female" @("Mary","Jane","Brenda")
$obj | select male
Frank John
----- ----
3 5
Why did this happend?
If you read the syntax for New-Object
using Get-help new-object
or Get-Command New-Object -Syntax
, you will see that for normal .Net types, the syntax is:
New-Object [-TypeName] <String> [[-ArgumentList] <Object[]>] [-Property <IDictionary>]
Notice that -ArgumentList
is the 2nd paramter, not -Property
as you expected. So your code actually did:
$obj = New-Object -TypeName PSObject -ArgumentList $props
instead of:
$obj = New-Object PSObject -Property $props
EDIT The solution above only worked in PS3.0 . It's still valid though, as the -Property
parameter is required in PS2.0 also. In PS2.0 you need to cast the propertyset-array to string[]
(string-array) and not an object-array (object[]
) which is the default array. A complete solution for PS2.0 is:
$props = @{"Mary"=1;"Jane"=2;"Frank"=3;"John"=5;"Brenda"=6}
$obj = New-Object -TypeName PSObject -Property $props
$obj | Add-Member PropertySet "Male" ([string[]]@("Frank","John"))
$obj | Add-Member PropertySet "Female" ([string[]]@("Mary","Jane","Brenda"))
$obj | select male
Frank John
----- ----
3 5