How to Map Users to Computers

One of the mini-challenges that comes up a lot is the question: “can we find out who is currently logged in on all of these desktops/laptops?”. This information could be relevant in many projects, be it desktop patching, some kind of migration, inventory, or hunting down RDP sessions with expired credentials that cause account lockouts.

There’s probably a million and a half ways to approach this task. Typically, companies have a software deployment solution similar to Microsoft System Center Configuration Manager, which allows among other things to inventory and discover this type of information.

But what if there is nothing on the network that can do this out of the box? In this case, there are PowerShell, scripting, coding, log parsing, and possibly other ways to approach this task.

Use WMI with VB.NET to Query Currently Logged On User

WMI has been around since the days of Windows NT 4.0. When it works, it provides a wealth of information about the system it is running on – including information about the currently logged on user(s).

All we need to do is hook WMI into a VB.NET project:

Imports System.Management

This imports the namespace we will be working with. You may have to add a reference to System.Management assembly in your VS project. Now the code:

    Private Function GetUser(ByVal computername As String) As String

        Dim wmiscope As ManagementScope
        Dim wmiquery As ObjectQuery
        Dim wmisearcher As ManagementObjectSearcher
        Dim wmicol As ManagementObjectCollection
        Dim wmiobj As ManagementObject
        GetUser = Nothing

            wmiscope = New ManagementScope("\\" & computername & "\root\cimv2")
            wmiquery = New ObjectQuery("SELECT * FROM Win32_ComputerSystem")
            wmisearcher = New ManagementObjectSearcher(wmiscope, wmiquery)
            wmicol = wmisearcher.Get()

            For Each wmiobj In wmicol
                    GetUser = wmiobj("UserName").ToString
                Catch exx As Exception
                End Try

        Catch ex As Exception
            GetUser = Nothing
        End Try

    End Function

This snippet shows the use of various WMI collections and objects that connect to a remote computer and perform a WMI query. I skipped garbage collection work to keep this sample shorter.

This code sample takes computer name variable and does the WMI related work. You would need to query computer objects from the network – Active Directory, for example. Or you could feed a text file. For a sample of how to connect to and query Active Directory, see this post.

WMI object model is extensive and information available through it is pretty massive. More information on WMI can be reviewed here (Microsoft MSDN).


Leave a Reply

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