What WMI query can count signed on users?
Q: I need to count how many users are signed on. Also, I need to know machine serial number. Please help me to construct the WMI query.
A: Make sure you have performed all the steps required to run WMI queries. WMI is an advanced topic.
WMI query to count signed-in users looks like this:
Select * from Win32_LogonSession Where LogonType = 10
LogonType 10 filters console users, or
Select * from Win32_LogonSession Where (LogonType = 2) OR (LogonType = 10)
to enumerate both console and RDP users.
However, single WMI query may not be enough to select proper data. In that case, using Script or Program monitor could be preferable. Cut and paste the contents of the below text area and save them under name users-list.vbs (alternately, download users-list.zip, unpack it and rename the file to users-list.vbs):
strComputer = "." Set objWMI = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") Set colOS = objWMI.InstancesOf ("Win32_OperatingSystem")'Get OS For Each objOS in colOS strName = objOS.Name Next If Instr(strName, "Windows 2000") > 0 Then 'For Windows 2000 Set colComputer = objWMI.ExecQuery("Select * from Win32_ComputerSystem") For Each objComputer in colComputer Wscript.Echo "User: " & objComputer.UserName Next Else 'Windows XP or later Set colSessions = objWMI.ExecQuery _ ("Select * from Win32_LogonSession Where LogonType = 10") 'Remote session WScript.Echo "Count of logons: " & colSessions.Count WScript.Echo "____________________________________" If colSessions.Count = 0 Then Wscript.Echo "No interactive user found" Else 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 "User: " & objItem.Name WScript.Echo "LogonId: " & objSession.LogonId Next WScript.Echo "" Next End If End If
You can run the above script from either Power Shell or cmd.exe console, using command like
cscript users-list.vbs
Use the script as template to add whatever checks or action you need. Refer to online help for details on monitor parameters of Script or Program monitor.
Similarly, serial number can be obtained with this script (save it under any suitable name):
strComputer = "." Set objWMI = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") Set colSMBIOS = objWMI.ExecQuery("Select * from Win32_SystemEnclosure") For Each objSMBIOS in colSMBIOS WScript.Echo "Serial number: " & objSMBIOS.SerialNumber Next
Note: “serial number” in this case refers to motherboard (system) serial number, if one is available.
Further reading: Microsoft WMI Reference (MSDN).