function Get-TSSession { param ( [string]$XPath = @" *[ System[(EventID=4624) or (EventID=4634)] and EventData[(Data[@Name='LogonType']=2) or (Data[@Name='LogonType']=10)] ] "@, [Parameter( ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] $ComputerName = $env:COMPUTERNAME ) process { Get-WinEvent -LogName security -ComputerName $ComputerName -FilterXPath $XPath ` | % { [xml]$_.ToXml()} ` | select @{n="EventID";e={$_.Event.System.EventID}}, @{n="ComputerName";e={$_.Event.System.Computer}}, @{n="TimeCreated";e={$_.Event.System.TimeCreated.SystemTime | Get-date}}, @{n="TargetUserSid";e={$_.Event.EventData.SelectSingleNode("*[@Name=""TargetUserSid""]").innertext}}, @{n="TargetUserName";e={$_.Event.EventData.SelectSingleNode("*[@Name=""TargetUserName""]").innertext}}, @{n="TargetDomainName";e={$_.Event.EventData.SelectSingleNode("*[@Name=""TargetDomainName""]").innertext}}, @{n="TargetLogonId";e={$_.Event.EventData.SelectSingleNode("*[@Name=""TargetLogonId""]").innertext}}, @{n="LogonType";e={$_.Event.EventData.SelectSingleNode("*[@Name=""LogonType""]").innertext}}, @{n="IpAddress";e={$_.Event.EventData.SelectSingleNode("*[@Name=""IpAddress""]").innertext}}, @{n="LogonGuid";e={$_.Event.EventData.SelectSingleNode("*[@Name=""LogonGuid""]").innertext}} ` | Group-Object -Property TargetLogonId ` | % { $logoff = $_.Group | ? EventID -eq 4634 $login = $_.Group | ? EventID -eq 4624 $out = if ($login) { $login | select * -ExcludeProperty "EventId","TimeCreated" } else { $logoff | select * -ExcludeProperty "EventId","TimeCreated" } $out | select *, @{n="LoginTime";e={$login.TimeCreated}}, @{n="LogoffTime";e={$logoff.TimeCreated}}, @{n="TimeElapse";e={ if ($logoff.TimeCreated -and $login.TimeCreated) { $d = (get-date $logoff.TimeCreated) - (get-date $login.TimeCreated) if ($? ) { $d.ToString("c") } } }}; } } } #Example # "server1","server2" | Get-TSSession |