Get the logged on users

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)}},             
 @{N="LogonTime";E={$data.ConvertToDateTime($data.StartTime)}}            
}            
}

 

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

Published Tue, Jan 17 2012 21:01 by RichardSiddaway

Comments

# re: Get the logged on users

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)

   }

}

Wednesday, January 18, 2012 8:49 AM by Rich Kusak

# re: Get the logged on users

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

Wednesday, January 18, 2012 10:50 AM by xxx

# re: Get the logged on users

For running the functions see

msmvps.com/.../running-a-function.aspx

Wednesday, January 18, 2012 1:31 PM by RichardSiddaway

# re: Get the logged on users

I've added some more information on using GetRelated() here msmvps.com/.../associated-classes.aspx

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

msmvps.com/.../wmi-associations-through-cim-cmdlets.aspx

Wednesday, January 18, 2012 1:57 PM by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: