Finding the currently logged on user using powershell and WMI

This is quick one for reference, here is an example how to find out currently logged on user on remote computer or local computer (administrative permission is required for querying remote computer) using PowerShell single liner:

Get-WmiObject win32_ComputerSystem -ComputerName Remote computer name or IP address | Select username
 
For finding out the currently logged on user, WMI and Win32_ComputerSystem class is used. Win32_ComputerSystem class has username property which contains the currently logged on user. For more information about Win32_ComputerSystem class please check the MSDN article http://msdn.microsoft.com/en-us/library/aa394102(v=vs.85).aspx .

My first thought was to find out the currently logged on user, but what about the users that are logged on and are switching between their profiles ? That's when the things get complicated. Anyway, here is PowerShell script which will list logged on users on remote or local machine, even if they are switching between profiles on same pc (for comp variable add the ip address or computer name of the machine, also administrative permission are required) :

$comp="computername or ip address"
Get-WmiObject win32_logonsession -ComputerName $comp -Filter "Logontype = '2' or Logontype='11' or logontype='10'" |
foreach {Get-WmiObject win32_loggedonuser -ComputerName $comp -filter "Dependent = '\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=`"$($_.logonid)`"'" | select Antecedent } |
foreach { ($_.antecedent.split('"'))[1] + "\" + ($_.antecedent.split('"'))[3] } | select -unique

WMI is utilized and Win32_LogonSession and Win32_LoggedOnUser classes are used. From Win32_LogonSession I'm filtering for following logontype: Interactive, RemoteInteractive and CachedInteractive, and passing the logonid to Win32_LoggedOnUser class. From Win32_LoggedOnUser class Antecedent property is manipulated to create easy to read output.

For more info about Win32_LogonSession and Win32_LoggedOnUser classes, please check MSDN library : http://msdn.microsoft.com/en-us/library/aa394172(v=vs.85).aspx and http://msdn.microsoft.com/en-us/library/aa394189(v=vs.85).aspx .

 

1 comment:

  1. In your post is a simple example for our convenience of how to use a PowerShell single liner to determine the user who is presently signed in on a local or distant computer administrator authority is required for searching remote computers. Today, my brother asked me How to write a dissertation proposal? so I suggested this site because i and my friends always use this site for our dissertation help and i will advise you please use this site for your dissertation writing their writers are very handworker who do our work in the right time.

    ReplyDelete

How to check EMBG (Unique Master Citizen Number) using regex

In this post, I will share my implementation of how to check if some number looks like EMBG or Unique Master Citizen Number. For those of yo...