3

How can I use VB scripting with WMI to get the # of logged in users. My installation can only have one user logged in and needs to report an error if more than one user is logged in (via terminal service using Citrix). I don't know that much about Citrix but the Win32_LogonSession with LogonType = 10 seems to return all kinds of junk (ports sessions, etc.). I just need the users...are there any WMI calls that I can just get the # of users logged into Citrix? Below is a snip of my VB code:

Set objWMIService = _
    GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\cimv2") 
Set colComputer = _
    objWMIService.ExecQuery("Select * from Win32_LogonSession Where LogonType = 10")

Thanks! -jp

Kev
  • 118,037
  • 53
  • 300
  • 385

1 Answers1

3

The following code should help you out (use strComputer="." for local computer or strComputer="MachineName"):

strComputer = "."   
Set objWMI = GetObject("winmgmts:" _ 
              & "{impersonationLevel=impersonate}!\\" _ 
              & strComputer & "\root\cimv2") 


Set colSessions = objWMI.ExecQuery _ 
    ("Select * from Win32_LogonSession Where LogonType = 10") 


If colSessions.Count = 0 Then 
   Wscript.Echo "No interactive users found" 
Else 
   WScript.Echo "RDP Sessions:"
   For Each objSession in colSessions 

     Set colList = objWMI.ExecQuery("Associators of " _ 
         & "{Win32_LogonSession.LogonId=" & objSession.LogonId & "} " _ 
         & "Where AssocClass=Win32_LoggedOnUser Role=Dependent" ) 
     For Each objItem in colList 
       WScript.Echo "Username: " & objItem.Name & " FullName: " & objItem.FullName 
     Next 
   Next 
End If 

The original code is here:

How to show logged on users? (Tek-Tips Forums)

This did work with Windows 2003, I can't make any guarantees about later version.

Kev
  • 118,037
  • 53
  • 300
  • 385
  • This doesn't really work, at least not in Win7 or 2008 R2. The code runs fine, but it returns multiple instances of the same account, and it reports accounts that maybe had logged on a long time ago, but are not logged on now. – Ryan Ries Aug 16 '13 at 19:26
  • @RyanRies - this answer was written in 2009, and given the original date of the source article linked to which was 2006, it probably only works with Windows 2000/2003. I will make this clearer in my answer. – Kev Aug 17 '13 at 04:11