PowerShell for Windows Admins

Jul 4 2019   10:19AM GMT

Logon sessions

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: