header image

Logon sessions

Posted by: | July 4, 2019 Comments Off on Logon sessions |

Saw a question about logon sessions that had me looking at CIM class Win32_LogonSession. I really don’t like the example code they have – code shouldn’t posted that contains aliases especially the abominable use of ? for Where-Object (pet PowerShell peeve number 3).


Something like this is a better example – especially as it demonstrates using CIM associations.

Get-CimInstance -ClassName Win32_Logonsession |
Where-Object LogonType -in @(2,10) |
ForEach-Object {

switch ($_.LogonType){
2 {$type = ‘Interactive Session’}
10 {$type = ‘Remote Session’}
default {throw “Broken! Unrecognised logon type” }

$usr = Get-CimAssociatedInstance -InputObject $psitem -ResultClassName Win32_Account
$props = [ordered]@{
Name = $usr.Name
Domain = $usr.Domain
SessionType = $type
LogonTime = $_.StartTime
Authentication = $_.AuthenticationPackage
Local = $usr.LocalAccount
if ($props.Name) {New-Object -TypeName PSobject -Property $props}


Get the instances of Win32_LogonSession where the LogonType is 2 (interactive) or 10 remote (RDP type session) and for each of them find the associated instance of Win32_Account (user information). Create the output object if the Win32_Account has the name property populated. This filters out historical sessions.


I could have used a Filter instead of Where-Object to perform the filtering but I may want to extend the number of types of session I include and doing it this way is easier than have a massive filter statement with lots of ORs

under: PowerShell and CIM

Comments are closed.