Group first, then print group's objects
The following example first groups an array of objects according to a given property value and then prints some property values of each object in the found groups:
[psCustomObject] @{ category = 'foo'; val_A = 4; val_B = 'abc' } ,
[psCustomObject] @{ category = 'foo'; val_A = 2; val_B = 'def' } ,
[psCustomObject] @{ category = 'bar'; val_A = 9; val_B = 'ghi' } ,
[psCustomObject] @{ category = 'foo'; val_A = 3; val_B = 'jkl' } ,
[psCustomObject] @{ category = 'baz'; val_A = 6; val_B = 'mno' } ,
[psCustomObject] @{ category = 'bar'; val_A = 7; val_B = 'pqr' } ,
[psCustomObject] @{ category = 'baz'; val_A = 5; val_B = 'stu' } |
#
# Pipe all objects into group-object to
# group theym by their category value:
#
group-object category |
#
# There are three different categories, so group-object
# produces three Microsoft.PowerShell.Commands.GroupInfo
# objects.
# These three objects are now piped into foreach-object
# which first prints the group's name, which is the value
# of the respective category, and then passes the group's
# Group value further down the pipeline:
#
foreach-object { write-host $_.Name; $_.Group } |
#
# A group's Group property contanis all object that
# belong to a group. These objects are now passed
# to the following foreach-object which simply
# prints the objects' properties val_A and val_B:
#
foreach-object { write-host " $($_.val_A): $($_.val_B)" }
-asHashTable
A nice option of
group-object
is
-asHashTable
: it returns a the grouped
objects as a
hash table whose keys correspond to the values of the grouped-by property.
In the following example, the
import-CSV
cmdLet is used to import the following
CSV file:
quarter,item,val
Q1,foo,17
Q1,bar,26
Q1,baz,15
Q2,foo,21
Q2,bar,18
Q2,baz,29
Q3,foo,9
Q3,bar,22
Q3,baz,16
Q4,foo,15
Q4,bar,18
Q4,baz,19
The imported CSV values (
$data
) is then grouped by the value of
quarter
and assigned to the
variable $quarters
.
$quarters.GetType().FullName
is used to verify that the returned value is indeed a hashtable (whose underlying type is a
System.Collections.Hashtable
).
Then, the (three) object of the third quarter (
$quarters.Q3
) are
piped through
where-object
to find the object whose
item
value is
baz
. This object's
val
value is then printed.
Finally, where-object
is used on the second quarter to find all objects whose val
value is greater or equal to 20 and then, their item
property is printed.
$data = import-CSV data.csv
$quarters = $data | group-object -asHashTable quarter
$quarters.GetType().FullName
#
# System.Collections.Hashtable
#
( $quarters.Q3 | where-object item -eq baz ).val
#
# 16
#
( $quarters.Q2 | where-object val -ge 20 ) | select-object item
#
# item
# ----
# foo
# baz
#