# getLoginEvents.ps1
function getLoginEvents{
param(
$computername=$env:computername,
$daysLimit=30
)
$ErrorActionPreference='stop'
try{
$logins=Get-WinEvent -ComputerName $ComputerName -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"| `
?{$_.ID -match '21|25' -and $_.TimeCreated -ge (get-date).AddDays(-$daysLimit)}| `
Select Id,TimeCreated, Message
$loginEvents=[System.Collections.ArrayList]::new()
Foreach ($login in $logins){
$loginTime = $login.TimeCreated
$eventId=$login.Id
$loginType=switch ($eventId){
'21'{'New Session';break}
'25'{'Reconnection';break}
}
$x = $login.Message -split "`n"
$user = ($x|Select-Object -Index "2").Substring(6)
$source=($x|Select-Object -Index "4").Substring(24)
$null=$loginEvents.Add([PSCustomObject]@{
loginTime = $loginTime;
username = $user;
loginType=$loginType;
loginSource = $source;
})
}
return $loginEvents
}
catch{
write-warning "$($error[0])"
return $null
}
}
getLoginEvents
# Sample Output
#
#loginTime username loginType loginSource
#--------- ---- --------- ---------
#7/3/2020 9:34:35 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.127
#7/3/2020 9:34:19 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.66
#7/3/2020 8:57:44 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.127
#7/3/2020 5:59:24 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.66
#7/3/2020 3:42:04 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.66
#7/2/2020 9:20:19 PM KIMCONNECT\RAMBO1... Reconnection 192.168.0.66
July 4, 2020July 4, 2020
0 Comments