header image

Get the logged on users

Posted by: | January 17, 2012 | 5 Comments |

Do you know which users are logged on to your systems?

Want to find out?

function get-logedonuser {            
param (            
 [string]$computername = $env:COMPUTERNAME            
Get-WmiObject -Class Win32_LogonSession -ComputerName $computername |            
foreach {            
 $data = $_            
 $id = $data.__RELPATH -replace """", "'"            
 $q = "ASSOCIATORS OF {$id} WHERE ResultClass = Win32_Account"            
 Get-WmiObject -ComputerName $computername -Query $q |            
 select @{N="User";E={$($_.Caption)}},             


Use the Win32_LogonSession class and then find the associated Win32_Account classes.  It does work for domain and local accounts

under: PowerShell and WMI, PowerShellV2


  1. By: Rich Kusak on January 18, 2012 at 8:49 am      

    Good stuff Richard. Thought I’d include another possiblity without the associators query, it’s a bit messy.

    $logonSessions = Get-WmiObject Win32_LogonSession

    foreach ($logonSession in $logonSessions) {
    $account = $logonSession.GetRelated(‘Win32_Account’)

    New-Object PSObject -Property @{
    ‘User’ = $account | Select -ExpandProperty Caption
    ‘LogonTime’ = $logonSession.ConvertToDateTime($logonSession.StartTime)

  2. By: xxx on January 18, 2012 at 10:50 am      

    Do you have a Primer on how to get set up so you can actually use these functions? Thanks.

  3. By: RichardSiddaway on January 18, 2012 at 1:31 pm      

    For running the functions see

  4. By: RichardSiddaway on January 18, 2012 at 1:57 pm      

    I’ve added some more information on using GetRelated() here http://msmvps.com/blogs/richardsiddaway/archive/2012/01/18/associated-classes.aspx

    and using associations with the new CIM cmldets in PowerShell v3 here

  5. By: richardsiddaway on January 24, 2016 at 11:03 am      

    Just tested it again and it works on my machine – Windows 10 latest build

    What do you get returned?


  1. Why am I not getting my logon session from a WMI query? – Internet and Tecnnology Answers for Geeks