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

This entry was posted in PowerShell and CIM. Bookmark the permalink.

1 Response to Logon sessions

  1. Glenn Carr says:

    Do you have a list of PowerShell pet peeves that I’ve missed? I can guess, but what are your reasons for not liking ? for Where-Object?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s