Search This Blog

Showing posts with label WMI. Show all posts
Showing posts with label WMI. Show all posts

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

Monday, December 30, 2019

Using WMI in Python

Using WMI in Python

Two steps 
  1. Install pywin32 to support wmi commands 
  2. import wmi in python code

INSTALL PYWIIN32
  1. Open Python Terminal 
  2. Type pip install pywin32 and press enter. This will install pywin32
IMPORT WMI PYTHON

Like anyother import command you just need to use import wmi. Below is the sample code which get the list of services that is in stopped state (not running )

import wmi

c = wmi.WMI ()
for s in c.Win32_Service ():
  if s.State == 'Stopped':
    print(s.Caption, s.State)