Decrypt my World

Cryptography, Security, Debugging and more!

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

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

Rate This
  • Comments 21

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)

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

  • 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.

  • 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...

  • Do you get any error?

  • 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

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

  • what´s meaning "no interactive user found" ?

  • removing 'Where LogonType = 2' gave a better result for me under XP

  • 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")

  • I think I'm misunderstanding what LogonType 10 represents. Specifically,

    I'm trying to enumerate interactive logged-in users, both console

    and RDP, on WinXP and Win2003 machines. I get Type 10 sessions

    for the real logged-in users but also for people without RDP

    sessions (using Terminal Services Manager to verify who is

    logged in). I'm at a loss to explain what these other type

    10 sessions might be, and how to distinguish between them and

    "real" logins.

  • It does not report a username on W2K, for XP is great.

  • Thanks alot maaaaaan

    this is so useful

  • 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 it

    returns 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} com

    Thanks in advance!!

  • Sorry, I'm afraid I cannot attend personal requests. If you need urgent help, I suggest you contact MS Technical Support in your country.

    Thank you.

    Alex

  • I'm getting RPS server is not available at line 22 wich is this line

    Set objLocator = CreateObject("WbemScripting.SWbemLocator")

    Does anyone knows how to correct it?

Page 1 of 2 (21 items) 12
Leave a Comment
  • Please add 8 and 8 and type the answer here:
  • Post
Translate This Page