Share via


How to get the logged on user with WMI (VBScript)

Hi all, welcome back,

From time to time I get to do some scripting, play with LDAP/ADSI, WMI, etc. I'll begin posting some VBScript samples I have which may be useful for you too.

Today we'll see a way to get the user who has logged on a given machine with VBScript & WMI:

 

 ' PARAMETERS
'
strComputer = "machineName"   ' use "." for local computer 
strUser = "domain\user" ' comment this line for current user
strPassword = "password" ' comment this line for current user

' CONSTANTS
'
wbemImpersonationLevelImpersonate = 3
wbemAuthenticationLevelPktPrivacy = 6

'=======================================================================
' MAIN
'=======================================================================

' Connect to machine
'
If Not strUser = "" Then

   ' Connect using user and password
   '
   Set objLocator = CreateObject("WbemScripting.SWbemLocator")
 Set objWMI = objLocator.ConnectServer _
     (strComputer, "root\cimv2", strUser, strPassword)
   objWMI.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
 objWMI.Security_.AuthenticationLevel = wbemAuthenticationLevelPktPrivacy
    
Else

    ' Connect using current user
    '
   Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 

End If

' Get OS name
'
Set colOS = objWMI.InstancesOf ("Win32_OperatingSystem")

For Each objOS in colOS
    strName = objOS.Name
Next

If Instr(strName, "Windows 2000") > 0 Then

   '-------------------------------------------------------------------
    ' Code for Windows 2000
 '-------------------------------------------------------------------

    ' Get user name
 '
   Set colComputer = objWMI.ExecQuery("Select * from Win32_ComputerSystem")
    
    For Each objComputer in colComputer
     Wscript.Echo "User: " & objComputer.UserName
    Next

    ' ------------------------------------------------------------------
    
Else

    ' ------------------------------------------------------------------
    ' Code for Windows XP or later
  ' ------------------------------------------------------------------
    
    ' Get interactive session
   '
   Set colSessions = objWMI.ExecQuery _ 
         ("Select * from Win32_LogonSession Where LogonType = 2") 
 
    If colSessions.Count = 0 Then 
      ' No interactive session found
      '
       Wscript.Echo "No interactive user found" 
   Else 
       'Interactive session found
      '
       For Each objSession in colSessions 
     
            Set colList = objWMI.ExecQuery("Associators of " _ 
         & "{Win32_LogonSession.LogonId=" & objSession.LogonId & "} " _ 
         & "Where AssocClass=Win32_LoggedOnUser Role=Dependent" ) 
                   
            ' Show user info
            '
           For Each objItem in colList 
                WScript.Echo "User: " & objItem.Name 
               WScript.Echo "FullName: " & objItem.FullName 
               WScript.Echo "Domain: " & objItem.Domain 
           Next 
           
            ' Show session start time
           '
           Wscript.Echo "Start Time: " & objSession.StartTime 
     Next 
   End If 
 
    ' ------------------------------------------------------------------

End If

'=======================================================================

 

I hope this helps.

Cheers,

 

Alex (Alejandro Campos Magencio)

Comments

  • Anonymous
    March 04, 2008
    This is excellent.  There are many, many ways one could integrate this in to other tools.

  • Anonymous
    December 21, 2008
    Do not work on Vista.If one User is logged in, it found the User twice.If two Users are logged in, it found only one.

  • Anonymous
    February 24, 2009
    Hi,Thanks for the script, but even though I saved the text file with vbs extension, it didn't run either on Windows XP or Windows Server 2003...

  • Anonymous
    February 24, 2009
    Do you get any error?

  • Anonymous
    March 30, 2009
    Hi there,I have been trying to find out this very piece of information - thanks!.  However, now the bad news :(.  I am trying out the query using Wbemtest and I cannot seem to get access to domain based accounts when querying a remote host, but I CAN get them when running the command locally.  I have confirmed that the user I am connecting as is a member of the local administrators group.  Is there some extra level of restriction at play here, or am I missing something obvious.  Thanks, Andy

  • Anonymous
    April 08, 2009
    I'm also having the same issue as Andy McCall above, any pointers?

  • Anonymous
    May 05, 2009
    what´s meaning "no interactive user found" ?

  • Anonymous
    May 06, 2009
    removing 'Where LogonType = 2' gave a better result for me under XP

  • Anonymous
    August 05, 2009
    I had better luck replacing:("Select * from Win32_LogonSession Where LogonType = 2")With...("Select * from Win32_LogonSession where LogonType <> 0 and LogonType <> 3 and LogonType <> 5")

  • Anonymous
    August 12, 2009
    I think I'm misunderstanding what LogonType 10 represents. Specifically,I'm trying to enumerate interactive logged-in users, both consoleand RDP, on WinXP and Win2003 machines. I get Type 10 sessionsfor the real logged-in users but also for people without RDPsessions (using Terminal Services Manager to verify who islogged in). I'm at a loss to explain what these other type10 sessions might be, and how to distinguish between them and"real" logins.

  • Anonymous
    November 05, 2009
    It does not report a username on W2K, for XP is great.

  • Anonymous
    March 23, 2010
    Thanks alot maaaaaanthis is so useful

  • Anonymous
    April 14, 2010
    Hello, please help :)The script works for me only on local computer.When i try other computer in the domain the script returns nothing (i try it especialy on w2k3std terminal server).I've done some debugging and it looks like:Set colSessions = objWMI.ExecQuery _   ("Select * from Win32_LogonSession Where LogonType = 10 <-changed itreturns a number of objects which is very OK, but:Set colList = objWMI.ExecQuery("Associators of "  &"{Win32_LogonSession.LogonId=" & objSession.LogonId & "} " & "Where AssocClass=Win32_LoggedOnUser Role=Dependent" )returns nothing for any of them (agait - on local system it works)Do you have any idea why is that? It's not network problem. I also have admin rights on that system.You can contact me via emmmmail if you like: zbig83 [moonnkey] gmail {ddot} comThanks in advance!!

  • Anonymous
    April 14, 2010
    The comment has been removed

  • Anonymous
    June 03, 2010
    The comment has been removed

  • Anonymous
    August 19, 2010
    Works great. Odd things happen between W2K and the AD Server where I ran the script. Remember, if you aren't using the domain in the user entry, use the reference you are using to the remote system. If you used an IP to find it, use the IPusername for username.

  • Anonymous
    September 09, 2010
    The comment has been removed

  • Anonymous
    September 11, 2011
    I'm getting the same thing, Jim...if by RPS you mean RPC

  • Anonymous
    October 13, 2011
    Thanks for saving time. :) Works excelent!

  • Anonymous
    March 27, 2012
    Thanks the correction works well...Thanks Brian Kayser and the one who posted the code...

  • Anonymous
    July 03, 2013
    Say an user restarted his computer three days ago and logged in. Now he locks his computer every time he moves away from his system. So when I tried this code, it shows the login time as the one he logged in 3 days before and not the recent one when he unlocked his computer. How can we get this time? Please suggest...

  • Anonymous
    June 25, 2015
    <CODE> <# .Synopsis Get current logon sessions .Description Written by Edward Skarke 6/25/2015.  Addapted from a script posted in VBscript by Alejandro Campos Magencio 3/4/2008. .Link blogs.msdn.com/.../how-to-get-the-logged-on-user-with-wmi-vbscript.aspx #> $colSessions = Get-WmiObject -Query "Select * from Win32_LogonSession" # Where LogonType = 2" If ($colSessions.Count -eq 0)    { # No interactive session found # write-output "No interactive user found" }    Else    { #Interactive session found # foreach ($objSession in $colSessions) { $colList = get-wmiobject -query ("Associators of " + "{Win32_LogonSession.LogonId=" + $objSession.LogonId + "} " + "Where AssocClass=Win32_LoggedOnUser Role=Dependent")   # Show user info # ForEach ($objItem in $colList)            { $StartTime = get-date -Year $objSession.StartTime.Substring(0,4) -Month $objSession.StartTime.Substring(4,2) -Day $objSession.StartTime.Substring(6,2) -Hour $objSession.StartTime.Substring(8,2) -Minute $objSession.StartTime.Substring(10,2) -Second ($objSession.StartTime.Substring(12,2) +"." +($objSession.StartTime -split ".|-")[1])                $Record = New-Object psobject -Property @{Name=$objItem.Name;FullName=$objItem.FullName;Domain=$objItem.Domain;StartTime=$StartTime}                Get-Member -InputObject $objItem | ?{$.MemberType -like "property"} | %{                    $M = $.Name                    if (-not [bool]$Record.($M) -and [bool]$objItem.($M))                    {                        Add-Member -InputObject $Record -Name $M -MemberType NoteProperty -Value $objItem.($M)                    }                }                Get-Member -InputObject $objSession | ?{$.MemberType -like "property"} | %{                    $M = $.Name                    if (-not [bool]$Record.($M) -and [bool]$objSession.($M))                    {                        Add-Member -InputObject $Record -Name $M -MemberType NoteProperty -Value $objSession.($M)                    }                }                $Record                #write-output ("Usert: &quot; + $objItem.Name ) #write-output (&quot;FullName:t" + $objItem.FullName ) #write-output ("Domain:t&quot; + $objItem.Domain ) } # Show session start time # #write-output (&quot;Start Time:t" + $objSession.StartTime ) } } </CODE>

  • Anonymous
    November 05, 2015
    this will not work. Check out the following article why not: stale logon sessions. www.codeproject.com/.../Enumerating-Logon-Sessions