Perl – CPU and RAM Utilization of an application via WMI

In Perl, we can query the Windows Operating system using winmgmt service (A WMI Service) to get the CPU and RAM utilization of an application or process.

We can get the instance of winmgmt object in Perl using Win32::OLE library and run our select query to fetch the CPU and RAM utilization for a process using its Process ID or Process Name.

Using winmgmt we can perform almost all operations in a windows machine such as starting and stopping a windows service, getting the Operating System details, statists, network activity, storage management, etc…

Connecting to a WMI Service:

We can connect to a WMI Object in two ways

Retrieve an instance of an object using the GetObject function with a moniker string in the input parameter or

Create a SWbemLocator object, and then use the ConnectServer method to log on to a namespace.

A moniker is a standard COM mechanism for encapsulating the location and binding of another COM object. To connect to a WMI object using a moniker, pass the name of the WMI Scripting Library's moniker, which is "winmgmts:" followed by the name of the target computer as the parameter to the Perl GetObject function.

In the below example we have used //./ to indicated that we are connecting to the local computer. To connect to a remote computer replace the period(.) in //./ with remote computer name.

CPU% Utilization Formula:

p1 refers to the PercentProcessorTime value retrieved while executing the Win32_PerfRawData_PerfProc_Process query for the first time, and p2 refers to the data retrieved while querying for the second time. Whereas t1 and t2 refers to TimeStamp_Sys100NS values.