Jump to content

(NEWBIE GUIDE) How to access Win32 classes using objects


Gigglestick
 Share

Recommended Posts

This is a tutorial on how to access WMI Win32 classes using objects.

Here is the top-level class list from the MSDN: http://msdn.microsoft.com/library/en-us/wm...n32_classes.asp

Below is an example of how to use the Win32_Process class. See http://msdn.microsoft.com/library/default....n32_process.asp for the actual definition of the Win32_Process WMI class.

Here is our script in its entirety:

Dim $strComputer = "."
Dim $strFindProcess = "Notepad.exe"
Dim $objWMI, $colResults, $objItem, $intCount, $answer
$objWMI = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")
$colResults = $objWMI.ExecQuery("Select * from Win32_Process WHERE Name = '" & $strFindProcess & "'"); Note the single quotes
$intCount = $colResults
For $objItem in $colResults
    If $objItem.GetOwner(@UserName, @LogonDomain) = 0 Then
        $answer = MsgBox(1+64, $intCount & " Processes Found", @LogonDomain & "\" & @UserName & " is running notepad.exe" & @LF & _
            "The path is " & $objItem.ExecutablePath & @LF & _
            "It is running with a priority of " & $objItem.Priority & " (Max is 31 for highest priority)")
        If $answer = 2 Then ExitLoop; Cancel button
    EndIf
Next

Now let's break it down and explain the parts...

Our script begins by defining variables. For $strComputer, "." is the local computer, otherwise use the NETBIOS name or FQDN of a remote computer.

Dim $strComputer = "."
Dim $strFindProcess = "Notepad.exe"
Dim $objWMI, $colResults, $objItem, $intCount, $answer

Let's define the object that will run our query.

$objWMI = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")

Next, let's run our query, which results in a "collection". ExecuteQuery accepts standard TransactSQL querying commands (SELECT, FROM, WHERE, ORDER BY, etc.) See http://msdn.microsoft.com/library/en-us/ts...sqlcon_6lyk.asp for more info. For this example, we'll query for processes (executable programs) running on the computer that are named "notepad.exe" and do something with each of those processes. Note that, depending on your level of access (Administrator vs. User), you may or may not see processes belonging to other users (Services running as SYSTEM or other users logged onto a Terminal Services server).

$colResults = $objWMI.ExecQuery("Select * from Win32_Process WHERE Name = '" & $strFindProcess & "'"); Note the single quotes

Since $colResults is a collection, it automatically has a property of "Count".

$intCount = $colResults.Count

Now we can loop through our collection one item at a time. For each loop, $objItem will "be" one of the items in the $colItems collection and will have its own set of properties defined in the MSDN (See link above).

For $objItem in $colResults

Now let's do something with $objItem. Notice the methods in the definition at the bottom of this post. GetOwner requires a username and domain name and will return zero (0) if the process DOES belong to the user. It will return a non-zero value as an error, which you can lookup here.

If $objItem.GetOwner(@UserName, @LogonDomain) = 0 Then
        $answer = MsgBox(1+64, $intCount & " Processes Found", @LogonDomain & "\" & @UserName & " is running notepad.exe" & @LF & _
            "The path is " & $objItem.ExecutablePath & @LF & _
            "It is running with a priority of " & $objItem.Priority & " (Max is 31 for highest priority)")
    If $answer = 2 Then ExitLoop; Cancel button

This is the end of our For loop.

Next

That's all there is to it!

Now here is the definition of the Win32_Process WMI class from http://msdn.microsoft.com/library/en-us/wm...n32_process.asp. Any of the items between the brackets ("{}") can be used above, as in $objItem.ItemName. The string, uint16, datetime stuff indicates what type of data will be returned.

class Win32_Process : CIM_Process
{
  string Caption;
  string CommandLine;
  string CreationClassName;
  datetime CreationDate;
  string CSCreationClassName;
  string CSName;
  string Description;
  string ExecutablePath;
  uint16 ExecutionState;
  string Handle;
  uint32 HandleCount;
  datetime InstallDate;
  uint64 KernelModeTime;
  uint32 MaximumWorkingSetSize;
  uint32 MinimumWorkingSetSize;
  string Name;
  string OSCreationClassName;
  string OSName;
  uint64 OtherOperationCount;
  uint64 OtherTransferCount;
  uint32 PageFaults;
  uint32 PageFileUsage;
  uint32 ParentProcessId;
  uint32 PeakPageFileUsage;
  uint64 PeakVirtualSize;
  uint32 PeakWorkingSetSize;
  uint32 Priority;
  uint64 PrivatePageCount;
  uint32 ProcessId;
  uint32 QuotaNonPagedPoolUsage;
  uint32 QuotaPagedPoolUsage;
  uint32 QuotaPeakNonPagedPoolUsage;
  uint32 QuotaPeakPagedPoolUsage;
  uint64 ReadOperationCount;
  uint64 ReadTransferCount;
  uint32 SessionId;
  string Status;
  datetime TerminationDate;
  uint32 ThreadCount;
  uint64 UserModeTime;
  uint64 VirtualSize;
  string WindowsVersion;
  uint64 WorkingSetSize;
  uint64 WriteOperationCount;
  uint64 WriteTransferCount;
};

It has what are called "methods." Notice in the code above that we check for the owner by calling $objItem.GetOwner(...). A method is a function of the class that returns a value, just as the properties above do, except that methods require additional parameters. In the case of GetOwner, it wants you to specify a username and domain so it can tell if the process you're querying belongs to that user. In my example above, I just happen to use the current users info (@Username & @LogonDomain).

uint32 GetOwner(string User, string Domain);
uint32 SetPriority(sint32 Priority);
uint32 Terminate(uint32 Reason);

(There are other methods, but this subset will suffice for this example.)

My UDFs: ExitCodes

Link to comment
Share on other sites

2 points:

1) AutoIt (beta) doesn't have specific support for WMI; it has general support for COM objects, of which WMI is one.

2) Isn't this whole thread only applicable to the beta version of AutoIt? I don't think the current release version supports COM, does it? Anyway, if this applies to beta only, it might be good to specify that in your post so someone with the release version doesn't try your example and get frustrated with the (lack of) results.

My Projects:DebugIt - Debug your AutoIt scripts with DebugIt!
Link to comment
Share on other sites

  • 2 weeks later...
  • 5 years later...

Thank you!

"It has what are called "methods." Notice in the code above that we check for the owner by calling $objItem.GetOwner(...). A method is a function of the class that returns a value, just as the properties above do, except that methods require additional parameters."

That's what I needed to get my script going.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...