Pickle
Pickle

Reputation: 1124

Powershell get count of values in a column

#Function to get all user logons in the past 10 days
function get-logonhistory{
Param (
 [string]$Computer = (Read-Host Remote computer name),
 [int]$Days = 10
 )
 cls
 $Result = @()
 $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer
 If ($ELogs)
 { 
 ForEach ($Log in $ELogs)
 { If ($Log.InstanceId -eq 7001)
   { $ET = "Logon"
   }
   Else
   { Continue
   }
   $Result += New-Object PSObject -Property @{
    Time = $Log.TimeWritten
    'Event Type' = $ET
    User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])
   }
 }
 $Result | Select Time,"Event Type",User | Sort Time -Descending
 }
 Else
 { Write-Host "Problem with $Computer."
 Write-Host "If you see a 'Network Path not found' error, try starting the Remote Registry service on that computer."
 Write-Host "Or there are no logon/logoff events (XP requires auditing be turned on)"
 }
}

#list of usernames
get-logonhistory -Computer . | select User

The code above gives me a list of usernames. I want to get a count of each username and select the one with the highest count. How would I do this in Powershell?

Upvotes: 0

Views: 1267

Answers (1)

vrdse
vrdse

Reputation: 3154

Pipe your output object to Group-Object to group, then Sort-Object by Count and the first entry will be the username with highest count.

Get-LogonHistory | Group-Object -Property User | Sort-Object -Property Count | Select-Object -First 1

Upvotes: 2

Related Questions