Group Object - PowerShell


Overview

Group-Object groups objects in an array or collection into new objects based on specified property values, making it a powerful tool for organizing and summarizing data in PowerShell.

Syntax

Group-Object [-Property] <String[]> [-InputObject] <PSObject[]> [-AsHashTable] [-HasMoreData] [-ExcludeDuplicates] [-NoElement] [-ErrorAction] <ActionPreference> [-WarningAction] <ActionPreference> [-InformationAction] <ActionPreference> [-Verbose] [-Debug] [-ErrorVariable] <String> [-WarningVariable] <String> [-InformationVariable] <String> [-OutVariable] <String> [-OutBuffer] <Int32> [-PipelineVariable] <String>

Options/Flags

  • -Property <String[]>: Specify the property or properties used to group the objects.
  • -InputObject <PSObject[]>: Provide custom input objects to group.
  • -AsHashTable: Return the results as a hash table, with property values as keys and grouped objects as values.
  • -HasMoreData: Check if more data is available in the pipeline.
  • -ExcludeDuplicates: Only include unique property values in the grouping.
  • -NoElement: Avoid creating new objects for empty groups.
  • -ErrorAction, -WarningAction, -InformationAction : Control how errors, warnings, and informational messages are handled.
  • -Verbose, -Debug: Display additional output for debugging and troubleshooting.
  • -ErrorVariable, -WarningVariable, -InformationVariable : Assign specific variables to capture errors, warnings, and information messages.
  • -OutVariable : Store the output in a specified variable.
  • -OutBuffer : Control the maximum number of objects to buffer before outputting them.
  • -PipelineVariable : Use a variable to store the command output in the pipeline.

Examples

Example 1: Group objects by a single property

$groups = Group-Object -Property "Name" $computerNames

Example 2: Group objects by multiple properties

$groups = Group-Object -Property "Name", "OperatingSystem" $computerNames

Example 3: Return results as a hash table

$hashGroups = Group-Object -Property "Name" -AsHashTable $computerNames

Example 4: Exclude duplicate property values

$groups = Group-Object -Property "Name" -ExcludeDuplicates $computerNames

Common Issues

  • Ensure the specified property exists in the input objects.
  • Handle duplicate property values appropriately using -ExcludeDuplicates or -NoElement.
  • Consider the impact of grouping on the performance and memory consumption of your script.

Integration

Combine with Select-Object to display specific properties of grouped objects:

Group-Object -Property "Name" $computerNames | Select-Object -Property "Name", "Count"

Use with ForEach-Object to process each group separately:

Group-Object -Property "Name" $computerNames | ForEach-Object {
  Write-Host "Group Name:" $_.Name
  $_.Group | ForEach-Object {
    Write-Host "  " $_.Name
  }
}