Search code examples
powershellgroup-object

Group-Object AsHashTable doesn't work for ScriptProperty


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

Solution

  • 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