This is just a code fragment for something that took me some time to figure out. What I wanted to do is to count a pair of items. The data was coming from a CSV file, and one of the two values is calculated.
The code is:
#Make arrays the lazy way, splitting string
$UserList = "Shari,Richard,Alan".Split(",")
$PCList = "Comp1,Comp2,Comp3,Comp4".Split(",")
#Do this 100 times
$List = (1 ..100) |
foreach {
#Get Random PC and User Name
$PCName = Get-Random $PCList
$UserName = Get-Random $UserList
#Put them into a PSCustomObject
[PSCustomObject]@{"PCName"=$PCName;"UserName"=$UserName}
}
#Take the List, Group by PCName and Username, Sort ...
$List | group -Property PCName, UserName |
sort -Property name |
#This converts 'name' to Logons in display and gets count property added by Group
Select @{Label="Logons";Expression={$_.name}}, count |
ft -AutoSize
If you run the code, you will get results like this:
Logons | Count |
---|---|
Comp1, Alan | 9 |
Comp1, Richard | 11 |
Comp1, Shari | 8 |
Comp2, Alan | 10 |
Comp2, Richard | 8 |
Comp2, Shari | 5 |
Comp3, Alan | 3 |
Comp3, Richard | 6 |
Comp3, Shari | 9 |
Comp4, Alan | 11 |
Comp4, Richard | 10 |
Comp4, Shari | 10 |