ListLoggedOnUsers.vbs

'=========================================================================
' ListLoggedOnUsers.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/1/2011
' COMMENTS: Pass a Computer Name or IP to the Function and it will return
' the name computer name, # logged on users, and username of the logged on
' users. This works for local, remote, and RDP sessions.
' EXAMPLE: Wscript.Echo ListCurrentLoggedOn("computer")
' Wscript.Echo ListCurrentLoggedOn("192.168.1.100")
'=========================================================================
Option Explicit
Wscript.Echo ListLoggedOnUsers("computer")

Private Function ListLoggedOnUsers(strComputer)

    On Error Resume Next

    ' Determine Logged On Users By Owner of Explorer.exe Process
    Dim objWMIService: Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Dim colProcess: Set colProcess = objWMIService.ExecQuery("Select * from Win32_Process Where Name='explorer.exe'")
    Dim objProcess, colProperties, strUser, strDomain, strResult
    If colProcess.Count = 0 Then
        strResult = "Computer:" & strComputer & vbTab & "Count:" & colProcess.Count & vbTab & "User:N/A"
    Else
        Dim i: i = 1
        For Each objProcess in colProcess
            colProperties = objProcess.GetOwner(strUser,strDomain)
            strResult = strResult & "Computer:" & strComputer & vbTab & "Count:" & i & vbTab & "User:" & strDomain & "\" & strUser & vbCrLf
            i = i + 1
        Next
    End If

    'Check For Errors
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "Computer:" & strComputer & vbTab & "Count:!~ERROR~!" & vbTab & "User:!~ERROR~!"
    End If

    'Cleanup
    Set objWMIService = Nothing
    Set colProcess = Nothing

    'Return Result
    ListLoggedOnUsers = strResult

    On Error Goto 0

End Function

 

Leave a Reply

Your email address will not be published. Required fields are marked *