3

Works:

$Names = 1..5 | % { new-object psobject | add-member -Type NoteProperty -Name Name -Value "MyName" -PassThru } | group Name -AsHashTable
$Names.MyName

Doesn't work:

$Names = 1..5 | % { new-object psobject | add-member -Type ScriptProperty -Name Name -Value {"MyName"} -PassThru } | group Name -AsHashTable
$Names.MyName
xinglong
  • 115
  • 1
  • 5

1 Answers1

2

The reason you're unable to access the values in the hash-table by prop name or key-based access is that the keys/props are wrapped in PSObjects. There was a Github issue to fix this in Powershell Core, but it will likely remain forever in Windows Powershell.

If you want to convert to a hash-table after grouping, and want to access some of the grouped values by property name or key-based access do this:

$Names = 1..5 | ForEach-Object { 
    New-Object PsObject | Add-Member -Type ScriptProperty -Name Name -Value { return "MyName"} -PassThru 
} | Group-Object -Property 'Name' -AsHashTable -AsString
$Names.MyName 
$Names['MyName'] 


If you want to convert to a hash-table after grouping, and want to access all the grouped values at once, do this:

$Names = 1..5 | ForEach-Object { 
    New-Object PsObject | Add-Member -Type ScriptProperty -Name Name -Value { return "MyName"} -PassThru 
} | Group-Object -Property 'Name' -AsHashTable
$Names.Values


If you're not converting to a hash-table after the grouping, and want to access the data in $Names.Group, you'll need to expand that property.

$Names = 1..5 | % { 
    new-object psobject | add-member -Type ScriptProperty -Name Name -Value {"MyName"} -PassThru 
} | Group-Object -Property 'Name' 
$Names | Select-Object -ExpandProperty Group
derekbaker783
  • 8,109
  • 4
  • 36
  • 50
  • @xinglong, I edited the answer so that the solution works when `-AsHashTable` is used. – derekbaker783 May 03 '20 at 00:36
  • 1
    I know $Names.Values works, but since it is hash table, why $Names.Keys and $Names.Values work, but $Names["MyName"] and $Names.MyName don't? – xinglong May 03 '20 at 00:54
  • @xinglong, I added an explanation of the key/prop access issue, and code that will allow key/prop based access for your example. Please accept my answer if you have no further questions. – derekbaker783 May 03 '20 at 11:18