Remember to CP the script to the server and run remotely…
#Gets every connection made, but only the last one, in the last 30 days
$LogonEvents = Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624,4625,4634,4647;StartTime=$30DaysAgo} -ErrorAction SilentlyContinue
$ConnectionEvents = Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-TerminalServices-LocalSessionManager/Operational';ID=21,23;StartTime=$30DaysAgo} -ErrorAction SilentlyContinue
if($LogonEvents -or $ConnectionEvents) {
$Results = @()
foreach($Event in $LogonEvents) {
$User = $Event.Properties[5].Value
$Results += [PSCustomObject]@{
Time = $Event.TimeCreated
Type = $Event.Id
User = $User
Computer = $Event.MachineName
}
}
foreach($Event in $ConnectionEvents) {
$User = $Event.Properties[0].Value
$Results += [PSCustomObject]@{
Time = $Event.TimeCreated
Type = $Event.Id
User = $User
Computer = $Event.MachineName
}
}
$LastEvents = $Results | Sort-Object Time -Descending | Group-Object User | ForEach-Object { $_.Group | Sort-Object Time -Descending | Select-Object -Last 1 }
$LastEvents | Sort-Object Time -Descending
}
else {
Write-Host "No logon or connection events found in the last 30 days."
}
You HAVE to cp this script to the server and then run remotely in PowerShell 5.1, so make sure your $profile creates the structure you need. 🙂
powershell -File '\\hostname\D$\PowerShell\Get-loggedonUsers-Last30days-With-Get-WinEvent.ps1' -NoLogo -NoExit
NOTE: The runs from your $Env:UserProfile so edit the right one! 🙂