Search This Blog

Thursday, January 2, 2020

WMI to Get Logged on User - VB.NET

Below is the function to get the logged on user using WMI in VB.net.
This function checks for the process explorer.exe and then gets the owner of the process. explorer.exe will be actively running for the user who is currently logged on. Please remember that this WMI query might take cpu upto 3%

 Function GetUserName() As String

        Dim moReturn As Management.ManagementObjectCollection
        Dim moSearch As Management.ManagementObjectSearcher
        Dim mo As Management.ManagementObject
        'This scrolls through all the running processes on the PC to determine who is running the "explorer.exe" process. It then returns the username ready for comparison.
        moSearch = New Management.ManagementObjectSearcher("Select * from Win32_Process")
        moReturn = moSearch.Get
        For Each mo In moReturn
            Dim arOwner(2) As String
            mo.InvokeMethod("GetOwner", arOwner)
            Dim strOut As String
            strOut = String.Format("{0} Owner {1} Domain {2}", mo("Name"), arOwner(0), arOwner(1))
            If (mo("Name") = "explorer.exe") Then
                strCurrentUser = String.Format("{0}", arOwner(0))
            End If
        Next
    End Function

No comments:

Post a Comment