一个很晚的回复,但我希望它可以帮助需要计算对象的人。
让我们从我们希望计算的用户列表开始。
> $users = 1..10 | % {New-object psobject -Property @{ Name = "User $_"; Age = $_ } }
> $users
Age Name
--- ----
1 User 1
2 User 2
3 User 3
4 User 4
5 User 5
6 User 6
7 User 7
8 User 8
9 User 9
10 User 10
要计算它们,请将它们放入计数器的哈希表中
> # Create hash table
> $counter = @{}
> # Assign users as keys in the table
> $users | % { $counter.Add($_, 0) }
> $counter
Name Value
---- -----
@{Age=4; Name=User 4} 0
@{Age=1; Name=User 1} 0
@{Age=3; Name=User 3} 0
@{Age=5; Name=User 5} 0
@{Age=10; Name=User 10} 0
@{Age=9; Name=User 9} 0
@{Age=8; Name=User 8} 0
@{Age=7; Name=User 7} 0
@{Age=6; Name=User 6} 0
@{Age=2; Name=User 2} 0
然后,您可以在脚本中遇到用户时递增计数器。例如,要增加“用户 1”两次和一次“用户 4”
> $counter[$users[0]] += 1
> $counter[$users[0]] += 1
> $counter[$users[3]] += 1
> $counter
Name Value
---- -----
@{Age=4; Name=User 4} 1
@{Age=1; Name=User 1} 2
@{Age=3; Name=User 3} 0
@{Age=5; Name=User 5} 0
@{Age=10; Name=User 10} 0
@{Age=9; Name=User 9} 0
@{Age=8; Name=User 8} 0
@{Age=7; Name=User 7} 0
@{Age=6; Name=User 6} 0
@{Age=2; Name=User 2} 0