#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
上面的代码给了我一个用户名列表。我想得到每个用户名的计数,并选择计数最高的用户名。我如何在Powershell中做到这一点?
答案 0 :(得分:2)
将输出对象传输到Group-Object
组,然后Sort-Object
加Count
,第一个条目将是最高计数的用户名。
Get-LogonHistory | Group-Object -Property User | Sort-Object -Property Count | Select-Object -First 1