Sam Jacobs
asked on
How can I extract information from grouped records?
I would like to create a report of the number of users coming in from a particular IP address and their subnet. Consider the following test data:
Grouping the above by Subnet and IP should give me a report something like this:
So I use the Group-Object cmdlet:
Now, I can do this:
which will correctly output what I expect:
But if I do this (which I would expect is the same thing):
I don't get any output.
What am I doing wrong?
Thanks.
$users = @()
$users += [PSCustomObject]([ordered]@{Name='Adam';IP='192.168.4.1';subnet='192.168.4.x'})
$users += [PSCustomObject]([ordered]@{Name='Tony';IP='192.168.5.20';subnet='192.168.5.x'})
$users += [PSCustomObject]([ordered]@{Name='Cheryl';IP='192.168.4.1';subnet='192.168.4.x'})
$users += [PSCustomObject]([ordered]@{Name='Bob';IP='192.168.3.5';subnet='192.168.3.x'})
$users += [PSCustomObject]([ordered]@{Name='Sandy';IP='192.168.5.20';subnet='192.168.5.x'})
$users
This creates my array of users:Grouping the above by Subnet and IP should give me a report something like this:
So I use the Group-Object cmdlet:
$counts = $users | group subnet, IP
$counts
and that produces this:Now, I can do this:
Write-Host "$($Counts[0].Group[0].Subnet) $($Counts[0].Group[0].IP) $($counts[0].Count)"
Write-Host "$($Counts[1].Group[0].Subnet) $($Counts[1].Group[0].IP) $($counts[1].Count)"
Write-Host "$($Counts[2].Group[0].Subnet) $($Counts[2].Group[0].IP) $($counts[2].Count)"
which will correctly output what I expect:
192.168.4.x 192.168.4.1 2
192.168.5.x 192.168.5.20 2
192.168.3.x 192.168.3.5 1
But if I do this (which I would expect is the same thing):
$counts | ForEach {
Select -Property {
@{n='Subnet'; e={$_.Group[0].Subnet}},
@{n='IP Address'; e={$_.Group[0].IP}},
@{n='# Users'; e={$_.Group[0].Count}}
}
}
I don't get any output.
What am I doing wrong?
Thanks.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER