If I have a list of objects
$o1 = New-Object –TypeName PSObject –Property @{"MyKey"= "dog"; "MyValue"="Steve"}
$o2 = New-Object –TypeName PSObject –Property @{"MyKey"= "dog"; "MyValue"="Frank"}
$o3 = New-Object –TypeName PSObject –Property @{"MyKey"= "fish"; "MyValue"="Frank"}
$inputs = ($o1, $o2, $o3)
And a function that groups them into a table and then displays them
Function Report
{
param($records)
$hashtable = $records | Group-object -AsHashTable -Property "MyKey"
Write-host "Format table:"
$hashtable | format-table
Write-host "Contains key:"
$hashtable.Keys | %{ "Key '$_' found: " + $hashtable.ContainsKey($_) }
}
So when I run this over my input list
Report($inputs)
I get
Name Value
---- -----
dog {@{MyKey=dog; MyValue=Steve}, @{MyKey=dog; MyValue=Frank}}
fish {@{MyKey=fish; MyValue=Frank}}
Contains key:
Key 'dog' found: True
Key 'fish' found: True
As I would expect.
I can now run my list through select-object
Report($inputs | select-object -Property MyKey, MyValue )
and get the same output from Report
as above.
However if I use an expression for the MyKey
value:
Report( $inputs | select-object -Property `
@{ Label = "MyKey"; Expression = {$_.MyKey} },
MyValue )
I get a grouped table that looks the same, but doesn't allow me to access values by key:
Name Value
---- -----
dog {@{MyKey=dog; MyValue=Steve}, @{MyKey=dog; MyValue=Frank}}
fish {@{MyKey=fish; MyValue=Frank}}
Contains key:
Key 'dog' found: False
Key 'fish' found: False
Why can't I access this hashtable by key?
Note that this question looks a lot like this one but that solution did not work here. That is:
Add-Type -TypeDefinition @'
public static class Helper {
public static object IndexHashtableByPSObject(System.Collections.IDictionary table,object[] key) {
return table[key[0]];
}
}
'@
Function Report
{
param($records)
$hashtable = $records | Group-object -AsHashTable -Property "MyKey"
$hashtable.Keys | %{ "Get using helper:" + [Helper]::IndexHashtableByPSObject($hashtable,$_) }
$hashtable.Keys | %{ "Get using reflection:" + [Collections.IDictionary].InvokeMember('','GetProperty',$null,$hashtable,$_) }
}
returns
Get using helper:
Get using helper:
Get using reflection:
Get using reflection:
am I implementing those solutions wrong?