Reputation: 619
I try to count the number of drives on certain VM's
in a Cluster:
(Get-ClusterGroup -Cluster <Name> |
Where-Object {$_.GroupType –eq 'VirtualMachine'} |
Get-VM |
Measure-Object -Property Harddrives).Count
--> Returns 55, the count of
VM's
in the Cluster
Several VM's have more than one Harddrive, how can I retrieve the proper Count of Drives in a pipelined command?
Upvotes: 4
Views: 4526
Reputation: 3181
I had a problem that was closer to the original question. I had a custom PowerShell object that I needed to literally count how many properties were in it. I found this:
($Object | Get-Member -MemberType NoteProperty | Measure-Object).Count
Upvotes: 4
Reputation: 19694
Try enumerating the property:
$harddrives = Get-ClusterGroup -Cluster '<String>' | ? GroupType -eq VirtualMachine |
Get-VM | % HardDrives
$harddrives.Count
Some shorthand in v4+:
(@(Get-ClusterGroup -Cluster '<String>').
Where({ $_.GroupType -eq 'VirtualMachine' }) |
Get-VM).HardDrives.Count
Upvotes: 3
Reputation: 440297
To complement TheIncorrigible1's helpful answer, which contains an effective solution but only hints at the problem with your Measure-Object
call:
Perhaps surprisingly, Measure-Object
doesn't enumerate input objects or properties that are themselves collections, as the following examples demonstrate:
PS> ((1, 2), (3, 4) | Measure-Object).Count
2 # !! The input arrays each counted as *1* object - their elements weren't counted.
PS> ([pscustomobject] @{ prop = 1, 2 }, [pscustomobject] @{ prop = 3, 4 } |
Measure-Object -Property prop).Count
2 # !! The arrays stored in .prop each counted as *1* object - their elements weren't counted.
The above applies as of Windows PowerShell v5.1 / PowerShell Core v6.1.0.
This GitHub issue suggests introducing a -Recurse
switch that would allow opting into enumerating collection-valued input objects / input-object properties.
Upvotes: 2