2

I'm trying to use Group-Object to group a list of objects based on a custom computation. A very simplified example is the following:

$groupedProjects = 1..10 | %{
    [PSCustomObject]@{
        ErrorMessage = if ($_ % 2) { 'SomeError' } else { '' } 
    }
} | Group-Object -Property { if ($_.ErrorMessage) { 'Failed' } else { 'Successful' } } -AsHashTable

$successGroup = $groupedProjects['Successful'] 
# $successGroup is null here instead of a list with the integers.

The problem is that the groups are not keyed by the string but by something else instead - not sure I really understand the problem.

PS: Using a script block is shown in the documentation in this manner:

1..35 | Group-Object -Property {$_ % 2},{$_ % 3}

so I'd assume the idea is valid - using integers instead of strings also works as intended. If there's a better way to do the above I'm all ears though.

Voo
  • 29,040
  • 11
  • 82
  • 156
  • Interesting. There is a larger discussion about this here: https://stackoverflow.com/questions/28190053/group-object-diffencies-with-or-without-code-block – Zerqent May 23 '18 at 11:26
  • You're using an implicit foreach in your group call with that scriptblock for a property... why? – Maximilian Burszley May 23 '18 at 12:48
  • You're also not passing any non-even numbers to your group call in the first place. You lack an else block in `ErrorMessage=` – Maximilian Burszley May 23 '18 at 12:50
  • @TheIncorrigle The missing else for the ErrorMessage was too much simplified, I'll fix it. Not sure what you mean with implicit foreach in the group-object script block. I'm using the script block for the property because I need a custom group property - how would you do it? – Voo May 23 '18 at 14:28

1 Answers1

2

The other posters are correct that the problem is with the key being stored as a PSObject but there is a build-in solution for this: use the -AsString switch along with -AsHashTable. This will force the key to be stored as a string.

I've opened an issue on GitHub for this bug.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Bruce Payette
  • 2,511
  • 10
  • 8