How to Get a List of Running Processes on Domain Computers

How to Get a List of Running Processes on Domain Computers Техника

Just about 80 various services are installed in the system with a standard Windows installation. And despite the fact that not all of them are launched automatically, the number of workers by default still seems too high, considering that a significant part of the total number of vulnerabilities ever discovered in this OS falls on system services. In addition, at home, many default services simply do not need to. For these and other reasons related to the optimization of the computer, it is recommended that you disable all services that you do not use.

Introduction

There are several ways in which you can access WMI data, and most of them use WQL queries. You can use several tools to execute WQL queries, the most accessible of which is a tool called WMI Tester (wbemtest.exe) — it is installed with Windows.

WMI Tester (Wbemtest.exe) is a tool that provides the basic functionality for executing WQL queries. You can run it by typing ‘wbemtest.exe‘ in the Run box:

Image 1

This opens the WMI Tester:

Image 2

You first need to connect to the WMI namespace that contains the class you want to query (Root\Cimv2 in most cases):

Image 3

Run the query by clicking the ‘Query’ or ‘Notification Query’ button:

Image 4

Enter the query text:

Image 5

Click the ‘Apply’ button. This opens a window with the query results:

Image 6

If the query is invalid, you will receive an error message:

Image 7

Getting a list of running processes on all endpoints is a very common task that is typically required in virus attack investigations, performance analysis and other projects. Win32 provides several ways to list running processes. Unfortunately, there is no single way to work on all Win32 platforms. Programmers have to combine several methods in one program so that it works on all versions of Windows. Information about running system processes should include Windows process name, process ID, executable file location and some other data.

System utilities, text and image editors, browsers and RSS aggregators, cryptographers and mail clients, all of these, and many other types of programs have one common function that does not depend on the purpose of the application, namely printing. For programs, one way or another dealing with content that can be displayed on analog media, the print function is considered almost non-mandatory.

But there are exceptions. Take, for example, the standard Windows Task Manager or process explorer remote computer. Despite the fact that the information displayed on processes tab may well be printed out, you will not find the usual ‘Print’ command in it. But what if you suddenly need to print a list of current processes? Do not rewrite them one by one into a text file! In fact, listing the processes, services, and other system information to a file (print) is very simple. The easiest way is to use special software, for example, Action1.

This manual describes actions to create a list of running processes.

1. Execute WMI Query in ROOT\CIMV2 Namespace:

– Launch WMI Explorer or any other tool which can run WMI queries.
– Run WMI query: SELECT * FROM Win32_Process

2. Open WMIC Command-line Interface:

– Press WIN+R
– Type “wmic”, press Enter
– In wmic command line tool type: /node:RemoteComputerName process

3. Run This Simple Windows Powershell Script:

– thru WMI object: Get-WmiObject -Namespace ROOT\CIMV2 -Class Win32_Process -Computer RemoteComputerName

5. Sort the Results Using the Line Below:

6. The Next Code Helps to Filter Results:

7. Save Results to CSV File:

8. The Next Step Is to Query Multiple Computers:

WMI (Windows Management Instrumentation) — это технология, с помощью которой можно получить и изменить достаточно широкий перечень параметров Windows.

Для примера мы хотим узнать информацию о процессоре. Мы можем использовать команду CMD sysinfo или Powershell Get-ComputerInfo, но увидеть только часть информации. С помощью WMI мы можем получить почти всю информацию.

Для получения всех классов WMI в Powershell мы можем использовать:

Get-WmiObject -List

Мы получим все классы для пространства имен root\cimv2 т.к. оно стоит по умолчанию. Если мы хотим использовать другое, то его нужно указать с ключом -Namespace.

Одной из особенностей этого командлета является, что мы можем получить все классы и свойства и исполнить методы на удаленном компьютере:

Get-WmiObject -List -ComputerName CL1

Где:
-ComputerName — имя компьютера

WMI работает на 135 порту, а так же привилегированная учетная запись с правами на WMI и DCOM.

Либо у нас должен работать PSRemoting (тогда мы будем использовать Ivoke-Command). Весь процесс описан тут

Получение свойств класса через Powershell WMI

Если мы еще не знаем какой класс нам нужен, а вывод очень большой, то мы можем немного отфильтровать результат. На примере я искал классы где в имени есть BIOS:

Get-WmiObject -List | where {$_.name -like "*BIOS*"}

 Если мы выведем свойства класса операционной системы, то не увидим названия:

Get-WmiObject -Class Win32_OperatingSystem

Получение класса WMI Powershell

Часть свойств можно получить и так:

[wmiclass]"Win32_OperatingSystem" | Get-Member

Для того что бы отобразить все свойства нужно выполнить:

Get-WmiObject -Class Win32_OperatingSystem | Select-Object -Property *

Получение всех свойств через WMI Powershell

Либо можно объявить результат в переменную:

$result = Get-WmiObject -Class Win32_OperatingSystem

Получить все значения переменной:

$result | Get-Member

Все значения WMI Powershell

И затем вызывать через переменную. Так я получу название:

$result.Caption

Поиск свойств в Powershell WMI

У нас два способа поиска нужных свойств. Первый через ключ -Filter:

Get-WmiObject -List | where {$_.Name -Like "*share*"}
Get-WmiObject -Class Win32_Share -Filter "Status = 'OK'"

Фильтрация свойств WMI Powershell

Но если мы напишем что-то не так, то увидим язык WQL (WMI Query Language):

Т.е. мы можем писать и запрос WQL:

Get-WmiObject -Query "SELECT * FROM Win32_share WHERE Status='OK'"

Вызов методов WMI через Powershell

Этот метод запустит Notepad.exe на удаленном компьютере AD. В $cred будут храниться учетные данные, если мы будем запускать процесс под другим пользователем.

$cred = Get-Credential
$process = Get-WmiObject -Query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" `
-Namespace "root\cimv2" -Computername 'AD' -Credential $cred
$process.Create( "notepad.exe" )

Есть другой подход, с другой командой:

Invoke-WmiMethod -Path win32_process -Name create -ArgumentList notepad.exe

Отмечу, что вызвать процесс в графической оболочке нельзя, он будет запущен в бэкграунде. Связано это с тем, что Microsoft против что бы вторгались в интерактивный сеанс пользователя кому-либо (не моя цитата). Один из вариантов решения этого помещать задачи в планировщике.

Для того что бы увидеть остальные команды по работе с WMI в Powershell можно запустить:

Get-Command -Noun *WMI*

Что бы увидеть примеры использования или получить справку:

Get-help Invoke-WmiMethod -Examples

Теги:

#powershell

#wmi

Windows-specific items

The table provides details on the item keys that are supported only by Zabbix Windows agent.

Item key details

Parameters without angle brackets are mandatory. Parameters marked with angle brackets < > are optional.

eventlog[name,<regexp>,<severity>,<source>,<eventid>,<maxlines>,<mode>]

The event log monitoring.
Return value: Log.

  • name — the name of the event log;
  • regexp — a regular expression describing the required pattern (case sensitive);
  • severity — a regular expression describing severity (case insensitive). This parameter accepts the following values: «Information», «Warning», «Error», «Critical», «Verbose» (running on Windows Vista or newer).
  • source — a regular expression describing the source identifier (case insensitive);
  • eventid — a regular expression describing the event identifier(s) (case sensitive);
  • maxlines — the maximum number of new lines per second the agent will send to Zabbix server or proxy. This parameter overrides the value of ‘MaxLinesPerSecond’ in zabbix_agentd.win.conf.
  • mode — possible values: all (default) or skip — skip the processing of older data (affects only newly created items).
  • The item must be configured as an active check;
  • The agent is unable to send in events from the «Forwarded events» log;
  • Windows Eventing 6.0 is supported;
  • Selecting a non-Log type of information for this item will lead to the loss of local timestamp, as well as log severity and source information;
  • See also additional information on log monitoring.

       
       
       
       
net.if.list

The network interface list (includes interface type, status, IPv4 address, description).
Return value: Text.

  • Multi-byte interface names supported;
  • Disabled interfaces are not listed;
  • Enabling/disabling some components may change their ordering in the Windows interface name;
  • Some Windows versions (for example, Server 2008) might require the latest updates installed to support non-ASCII characters in interface names.
perf_counter[counter,<interval>]

The value of any Windows performance counter.
Return value: Integer, float, string or text (depending on the request).

  • counter — the path to the counter;
  • interval — the last N seconds for storing the average value. The interval must be between 1 and 900 seconds (included) and the default value is 1.
  • interval is used for counters that require more than one sample (like CPU utilization), so the check returns an average value for last «interval» seconds every time;
  • Performance Monitor can be used to obtain the list of available counters.
  • See also: Windows performance counters.
perf_counter_en[counter,<interval>]

The value of any Windows performance counter in English.
Return value: Integer, float, string or text (depending on the request).

  • counter — the path to the counter in English;
  • interval — the last N seconds for storing the average value. The interval must be between 1 and 900 seconds (included) and the default value is 1.
  • interval is used for counters that require more than one sample (like CPU utilization), so the check returns an average value for last «interval» seconds every time;
  • This item is only supported on Windows Server 2008/Vista and above;
  • You can find the list of English strings by viewing the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009.
perf_instance.discovery[object]

The list of object instances of Windows performance counters. Used for low-level discovery.
Return value: JSON object.

  • object — the object name (localized).
Дополнительно:  Не могу поставить root права на андроид
perf_instance_en.discovery[object]

The list of object instances of Windows performance counters, discovered using the object names in English. Used for low-level discovery.
Return value: JSON object.

  • object — the object name (in English).
proc_info[process,<attribute>,<type>]

Various information about specific process(es).
Return value: Float.

  • process — the process name;
  • attribute — the requested process attribute;
  • type — the representation type (meaningful when more than one process with the same name exists)
  • The following attributes are supported:
    vmsize (default) — size of process virtual memory in Kbytes
    wkset — size of process working set (amount of physical memory used by process) in Kbytes
    pf — number of page faults
    ktime — process kernel time in milliseconds
    utime — process user time in milliseconds
    io_read_b — number of bytes read by process during I/O operations
    io_read_op — number of read operation performed by process
    io_write_b — number of bytes written by process during I/O operations
    io_write_op — number of write operation performed by process
    io_other_b — number of bytes transferred by process during operations other than read and write operations
    io_other_op — number of I/O operations performed by process, other than read and write operations
    gdiobj — number of GDI objects used by process
    userobj — number of USER objects used by process;
  • Valid types are:
    avg (default) — average value for all processes named <process>
    min — minimum value among all processes named <process>
    max — maximum value among all processes named <process>
    sum — sum of values for all processes named <process>;
  • io_*, gdiobj and userobj attributes are available only on Windows 2000 and later versions of Windows, not on Windows NT 4.0;
  • On a 64-bit system, a 64-bit Zabbix agent is required for this item to work correctly.

       
registry.data[key,<value name>]

Return data for the specified value name in the Windows Registry key.
Return value: Integer, string or text (depending on the value type)

  • key — the registry key including the root key; root abbreviations (e.g. HKLM) are allowed;
  • value name — the registry value name in the key (empty string «» by default). The default value is returned if the value name is not supplied.
  • Supported root abbreviations:
    HKCR — HKEY_CLASSES_ROOT
    HKCC — HKEY_CURRENT_CONFIG
    HKCU — HKEY_CURRENT_USER
    HKCULS — HKEY_CURRENT_USER_LOCAL_SETTINGS
    HKLM — HKEY_LOCAL_MACHINE
    HKPD — HKEY_PERFORMANCE_DATA
    HKPN — HKEY_PERFORMANCE_NLSTEXT
    HKPT — HKEY_PERFORMANCE_TEXT
    HKU — HKEY_USERS
  • Keys with spaces must be double-quoted.

       
registry.get[key,<mode>,<name regexp>]

The list of Windows Registry values or keys located at given key.
Return value: JSON object.

  • key — the registry key including the root key; root abbreviations (e.g. HKLM) are allowed (see comments for registry.data[] to see full list of abbreviations);
  • mode — possible values:
    values (default) or keys;
  • name regexp — only discover values with names that match the regexp (default — discover all values). Allowed only with values as mode.

Keys with spaces must be double-quoted.


       
       
service.discovery

The list of Windows services. Used for low-level discovery.
Return value: JSON object.

service.info[service,<param>]
  • service — a real service name or its display name as seen in the MMC Services snap-in;
  • paramstate (default), displayname, path, user, startup, or description.
  • Items like service.info[service,state] and service.info[service] will return the same information;
  • Only with param as state this item returns a value for non-existing services (255).

       
       
services[<type>,<state>,<exclude>]

The listing of services.
Return value: 0 — if empty; Text — the list of services separated by a newline.

  • typeall (default), automatic, manual, or disabled;
  • stateall (default), stopped, started, start_pending, stop_pending, running, continue_pending, pause_pending, or paused;
  • exclude — the services to exclude from the result. Excluded services should be listed in double quotes, separated by comma, without spaces.

       
       
vm.vmemory.size[<type>]

The virtual memory size in bytes or in percentage from the total.
Return value: Integer — for bytes; float — for percentage.

  • type — possible values: available (available virtual memory), pavailable (available virtual memory, in percent), pused (used virtual memory, in percent), total (total virtual memory, default), or used (used virtual memory)
  • The monitoring of virtual memory statistics is based on:
    • Total virtual memory on Windows (total physical + page file size);
    • The maximum amount of memory Zabbix agent can commit;
    • The current committed memory limit for the system or Zabbix agent, whichever is smaller.
wmi.get[<namespace>,<query>]

Execute a WMI query and return the first selected object.
Return value: Integer, float, string or text (depending on the request).

  • namespace — the WMI namespace;
  • query — the WMI query returning a single object.

WMI queries are performed with WQL.

wmi.getall[<namespace>,<query>]

Execute a WMI query and return the whole response. Can be used for low-level discovery.
Return value: JSON object

  • namespace — the WMI namespace;
  • query — the WMI query.

Мониторинг служб Windows

Это руководство содержит пошаговые инструкции по настройке мониторинга служб Windows. Предполагается, что Zabbix сервер и агент уже настроены и работают.

Шаг 1

Узнайте имя службы.

Вы можете получить имя, перейдя в оснастку MMC Службы и открыв свойства службы. На вкладке Общие вы должны увидеть поле, называемое ‘Имя службы’. Его значение и будет тем именем, которое вы будете использовать при настройке элемента данных для наблюдения.

Например, если вы хотите наблюдать службу «workstation», то ваша служба, вероятно, будет: lanmanworkstation.

Шаг 2

Настройте элемент данных для наблюдения за службой.

  • Ключ: serfice.info[lanmanworkstation]
  • Тип информации: Целочисленное (положительное)
  • Отображение значений: выберите преобразование значений Windows service state

Имеется два преобразования значений Windows service state и Windows service startup type, которые сопоставляют числовое значение в веб-интерфейсе его текстовому представлению.

Обнаружение служб Windows

Низкоуровневое обнаружение дает возможность автоматического создания элементов данных, триггеров и графиков по различных объектам на компьютере. Zabbix может автоматически начать наблюдение за службами Windows на вашей машине, без необходимости знания точного имени службы или создания элементов данных по каждой службе вручную. Можно использовать фильтр для генерирования реальных элементов данных, триггеров и графиков только по интересующим службам.

Overview

This section provides details on the Zabbix agent items that are supported on Windows. The supported items are presented in two tables:

  • Agent items — the agent item keys also supported on Windows
  • Windows-specific items — the item keys that are supported only on Windows:
  • eventlog/[/]
  • net.if.list
  • perf_counter/[/]
  • perf_counter_en/[/]
  • perf_instance.discovery/[/]
  • proc_info/[/]
  • service.discovery
  • service.info/[/]
  • services
  • wmi.get/[/]
  • wmi.getall/[/]
  • vm.vmemory.size/[/]

Windows-specific items sometimes are an approximate counterpart of a similar agent item, for example proc_info, supported on Windows, roughly corresponds to the proc.mem item, not supported on Windows.

Note that all item keys supported by Zabbix agent on Windows are also supported by Zabbix agent 2. See item keys supported by Zabbix agent 2 for additional item keys that you can use with the agent 2 only.

See also: Minimum permissions for Windows items

Agent items

The table below lists Zabbix agent items that are supported on Windows:

  • The item key is a link to full item details in the corresponding agent item group
  • The item key signature includes only those parameters that are supported on Windows
  • Windows-relevant item comments are included

email me

There are several ways in which you can access WMI data, and most of them use WQL queries. You can use several tools to execute WQL queries, the most accessible of which is a tool called WMI Tester (wbemtest.exe) – it is installed with Windows.

This article is a short tutorial that attempts to shed some light on several WQL aspects through a series of example WQL queries. I grouped the queries by their type.

  • Object Queries
  • Event Queries
  • Schema Queries

WMI Tester (Wbemtest.exe) is a tool that provides the basic functionality for executing WQL queries. You can run it by typing ‘wbemtest.exe‘ in the Run box.

This opens the WMI Tester.

You first need to connect to the WMI namespace that contains the class you want to query (Root\Cimv2 in most cases). Click the Connect button.

Run the query by clicking the ‘Query’ or ‘Notification Query’ button

Enter the query text.

Click the ‘Apply’ button. This opens a window with the query results:

If the query is invalid, you will receive an error message.

Object Queries

Object queries are used to get information about system resources.


 *  Win32_Process

This is probably the WQL query most often found in various WMI articles and textbooks. It simply gets all the instances of a WMI class named Win32_Process which represents Windows processes. If you are interested in the properties of Win32_Process, see here.


 *  Win32_Process 
 ProcessId = 

If you don’t really want all Windows processes, you can qualify your query using the WHERE clause. This clause looks like this:

 PropertyName Operator PropertyValue

where Operator is one of the WQL relational operators. The above query will return Win32_Process instances with process ID equals to 999.


 *  Win32_Process 
 Priority > 

One of the WQL relational operator is ‘>’ (greater than). The above query returns all Win32_Process instances with Priority greater than 9.


 *  Win32_Process 
 WriteOperationCount < 

This query returns all Win32_Process instances where the WriteOperationCount is less than 10000.


 *  Win32_Process  ParentProcessId <> 
 *  Win32_Process  ParentProcessId != 
 *  Win32_Process   ParentProcessId = 

All three queries return Win32_Process instances where ParentProcessId is not equal to 999.


 *  Win32_Service

Another commonly seen query that retrieves all information about Windows Services. See here for details about the Win32_Service class. Note that this query returns all class instances. Sometimes this is just what you want, other times it is not, and yet other times, this is something you should definitely avoid.


 *  Win32_Service 
 Name = 

Here is an improved query – it returns only Win32_Service instances that have the Name property equal to “MSSQL$SQLEXPRESS”. It happens that Name is the key property for the Win32_Service class, so the returned WMI object collection will have 0 or 1 item, but in general, if you qualify a query with a WMI class property value, you get all class instances where the property matches the entered value.

 *  Win32_Service 
 DisplayName = Plug and Play"

Here is a caveat. If you are familiar with Windows services, you know that you can access service information using Services.msc (Start > Run > Services.msc). When you open that applet, the text in the Name column is not equal to the Win32_Service.Name value. It is equal to the Win32_Service.DisplayName property value, so if you want to get services by their Services Control Panel applet name, use the above query.

Дополнительно:  Не работают USB порты на компьютере или ноутбуке Windows 10 — что делать? | remontka.pro

 *  Win32_Service 
 PathName = 

Here is another caveat. If a property value contains backslashes, you need to escape them by putting another backslash before (or after) each of them – otherwise, you get the ‘Invalid query’ error.


 *  Win32_Service 
 Name  

What if you don’t know the exact service name (or display name)? This is where the LIKE WQL operator comes in handy. Just like in SQL, the ‘%’ meta character replaces any string of zero or more characters, so this query returns all Win32_Service instances where the Name property contains the string “SQL”.


 *  Win32_Service 
 Name >   Name < 

You can use all WQL operators with string properties. This query returns all Win32_Service instances whose Name is greater than ‘M’ or less than ‘O’. The usual string comparison rules apply.


 *  Win32_Service 
 ExitCode = 

The Win32_Process.ExitCode property type is UInt32, but it is enclosed in quotes. WMI will does its best to interpret a string value and convert it to an appropriate type. This doesn’t work the other way – with string properties, you have to use quotes.


 *  Cim_DataFile 
 Drive =  
 Path = 

Cim_DataFile is a WMI class with which you should definitely always use the WHERE clause. ‘Select * From Cim_DataFile’ alone can take hours to complete, because it will return all files on your computer. Note that the Path property doesn’t contain file names or the drive letter which is stored in the Drive property.


Associators  {Win32_NetworkAdapter.DeviceId=1}
  • Win32_ComputerSystem
  • Win32_DeviceMemoryAddress
  • Win32_IRQResource
  • Win32_NetworkAdapterConfiguration
  • Win32_NetworkProtocol
  • Win32_PnPEntity
  • Win32_PortResource
  • Win32_SystemDriver

Associators  {Win32_NetworkAdapter.DeviceId=1} 
 ResultClass = Win32_NetworkAdapterConfiguration

Most of the time, you will not need all WMI objects associated with a WMI object. You can narrow the returned collection by specifying the class of the returned objects in an Associators Of query Where clause. The above query returns an instance of Win32_NetworkAdapterConfiguration associated with the source object.


Associators  {Win32_NetworkAdapter.DeviceId=1} 
 AssocClass = Win32_NetworkAdapterSetting

WMI classes are associated by a special type of WMI classes, called association classes. Win32_NetworkAdapterand Win32_NetworkAdapterConfiguration objects are associated by instances of the association class called Win32_NetworkAdapterSetting. As you can see, you can also use association class names to limit the returned object collection.


  {Win32_NetworkAdapter.DeviceId=1}
  • Win32_AllocatedResource
  • Win32_NetworkAdapterSetting
  • Win32_PnPDevice
  • Win32_ProtocolBinding
  • Win32_SystemDevices

Event Queries

Event queries are used for WMI event subscriptions.

 *  __InstanceCreationEvent 
Within  
 TargetInstance Isa 

This query is also often found in WMI samples. WMI event queries are different from other query types in that they don’t return WMI objects immediately. Instead of that, they are used for subscribing to WMI events, and objects are returned as events arrive. Note the two distinctive characteristics of event queries not present in other query types: the Within clause and the __InstanceCreationEvent class. The Within clause tells WMI how often to poll for events in seconds. In the above query, the polling interval is 5 seconds. WQL event monitoring consumes system resources, so it is important to balance between the need to get events on time and the need not to burden the system. The __InstanceCreationEvent class is one of the classes used only in event queries (other two commonly used classes are  __InstanceModificationEvent and  __InstanceDeletionEvent). An instance of this class is created when a requested event arrives. The __InstanceCreationEvent.TargetInstance property holds a reference to a WMI class that actually triggered the event. In the above query, it is the Win32_Process class, and we can use the TargetInstance property to access its properties.


 *  __InstanceCreationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

This query monitors the process creation event but only for processes named ‘Notepad.exe’.


 *  __InstanceDeletionEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

Use this query to monitor process deletion events for processes whose Name property is equal to ‘Notepad.exe’. A process deletion event occurs when a process exits. There is one thing you should note about a query like this: if you open Notepad and then quickly close it (within less than 5 seconds), it is possible for WMI to miss that and not report it as an event.


 *  __InstanceModificationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

This query monitors Win32_Process modification events, not the process modification event. This is an important distinction – if the Windows process entity has a property that is not represented with a Win32_Process WMI class, and if that property changes, WMI will not report the change. Only Win32_Processproperty changes are returned as WMI events.


 *  __InstanceOperationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

This query monitors all three types of events: creation, deletion, and modification events. The __InstanceOperationEvent class is the parent for the __InstanceCreation__InstanceDeletion, and __InstanceModification classes, and you can use this fact to subscribe to all three event types at the same time. The __InstanceOperationEvent class is abstract (which means that it doesn’t have instances), so the actual event class returned by an event is one of the tree instance classes, and you can find out which one by inspecting its __Class system property. This way, you can determine the event type.


Schema Queries

Schema queries are used to get information about WMI itself and its structure.


 *  Meta_Class

WMI namespace: Any.

This is the most basic schema query. You can connect to any WMI namespace and use this query to get all the classes present in it. Meta_Class is a meta class used only in schema queries.


 *  Meta_Class 
 __Class = 

This query uses the __Class system property to get the Win32_LogicalDisk class. Schema queries don’t return class instances, but class definitions, and a query like this will return a class definition regardless of whether there are any instances. Why would you want to get a class definition? New WMI classes are added for every new Windows version, and a query like this can check if a class exists on a system.


 *  Meta_Class 
 __Superclass  

WMI namespace: Any.

WMI is organized hierarchically – there is a hierarchy of namespaces as class containers, and there is a hierarchy of classes within each namespace. There is only one top level namespace called ‘Root’, but there is always more than one top level class in a namespace (even when you create a new empty namespace, a number of system WMI classes are created automatically). You can use this query to get all top level classes for a namespace. (This query also works if you use ‘=‘ instead of ‘Is‘.)


 *  Meta_Class 
 __Superclass = 

For each WMI class, the __Superclass property holds the name of its immediate parent class. You can use this query to return all immediate children classes of a class. Note the quotes around the class name. __Superclassis one of the seven WMI system properties (see details here), and you can use them in schema queries. All except one – the __Dynasty property is a string array, and you can’t use array properties in WQL queries. The above query returns two classes: Win32_LocalTime and Win32_UTCTime, the immediate children of Win32_CurrentTime.


 *  Meta_Class 
 __Dynasty = 

__Dynasty is another WMI system property – for each class, it holds the name of the top level class from which the class is derived. This query will return all children of Cim_Setting, a top level class situated in the Root\Cimv2 namespace.


 *  Meta_Class 
 __Class  

All WMI classes belong to a schema (or at least they should). For example, classes whose name begins with ‘Cim’ belong to the Cim schema, a group of ‘core and common’ WMI classes defined by DMTF. Classes that begin with ‘Win32’ belong to the ‘Win32’ schema – these classes are derived from Cim classes and extend them. You can use this query to list all classes that belong to the ‘Win32’ schema. The query uses the Like operator – this means, it can’t be used on Windows versions earlier than Windows XP, because the Like operator was added to WQL for XP.


 *  Meta_Class 
 __This Isa 

WMI namespace: Any.

This is not an event query despite the fact that it uses the __Event class. It is a schema query that lists all child classes (both direct and indirect) of __Event. Note the use of ‘__This’, a special WMI property used in schema queries, and the ‘Isa’ operator.


Manually

1. Execute WMI Query in ROOT\CIMV2 Namespace:

Launch WMI Explorer or any other tool which can run WMI queries.
Run WMI query: SELECT * FROM Win32_Service

2. Open WMIC Command-line Interface:

Press WIN+R
Type “wmic”, press Enter
In wmic command line tool type: /node:RemoteComputerName service

3. Run This Simple Windows Powershell Script:

Thru WMI object: Get-WmiObject -Namespace ROOT\CIMV2 -Class Win32_Service -Computer RemoteComputerName

4. Use Following Code to Select Specific Columns:

5. Sort the Results Using the Line Below:

6. The Next Code Helps to Filter Results:

7. Save Results to CSV File:

8. The Next Step Is to Query Multiple Computers:

Object Queries

Object queries are used to get information about system resources.


 *  Win32_Process 

WMI namespace: Root\Cimv2.

This is probably the WQL query most often found in various WMI articles and textbooks. It simply gets all the instances of a WMI class named Win32_Process which represents Windows processes. If you are interested in the properties of Win32_Process, see here.


 *  Win32_Process 
 ProcessId =  

WMI namespace: Root\Cimv2.

If you don’t really want all Windows processes, you can qualify your query using the WHERE clause. This clause looks like this:

 PropertyName Operator PropertyValue

where Operator is one of the WQL relational operators. The above query will return Win32_Process instances with process ID equals to 608.


 *  Win32_Process 
 Priority >  

WMI namespace: Root\Cimv2.

One of the WQL relational operator is ‘>’ (greater than). The above query returns all Win32_Process instances with Priority greater than 8.


 *  Win32_Process 
 WriteOperationCount <  

WMI namespace: Root\Cimv2.

This query returns all Win32_Process instances where the WriteOperationCount is less than 1000.

Дополнительно:  Замена на ноутбуке привода на HDD или SSD

 *  Win32_Process  ParentProcessId <> 
 *  Win32_Process  ParentProcessId != 
 *  Win32_Process   ParentProcessId = 

WMI namespace: Root\Cimv2.

All three queries return Win32_Process instances where ParentProcessId is not equal to 884.


 *  Win32_Service 

WMI namespace: Root\Cimv2.

Another commonly seen query that retrieves all information about Windows Services. See here for details about the Win32_Service class. Note that this query returns all class instances. Sometimes this is just what you want, other times it is not, and yet other times, this is something you should definitely avoid.


 *  Win32_Service 
 Name =  

WMI namespace: Root\Cimv2.

Here is an improved query – it returns only Win32_Service instances that have the Name property equal to “MSSQL$SQLEXPRESS”. It happens that Name is the key property for the Win32_Service class, so the returned WMI object collection will have 0 or 1 item, but in general, if you qualify a query with a WMI class property value, you get all class instances where the property matches the entered value.

 *  Win32_Service 
 DisplayName = Plug and Play" 

WMI namespace: Root\Cimv2.

Here is a caveat. If you are familiar with Windows services, you know that you can access service information using Services.msc (Start->Run-> Services.msc). When you open that applet, the text in the Name column is not equal to the Win32_Service.Name value. It is equal to the Win32_Service.DisplayName property value, so if you want to get services by their Services Control Panel applet name, use the above query.


 *  Win32_Service 
 PathName =  

WMI namespace: Root\Cimv2.

Here is another caveat. If a property value contains backslashes, you need to escape them by putting another backslash before (or after) each of them – otherwise, you get the ‘Invalid query’ error.


 *  Win32_Service 
 Name   

WMI namespace: Root\Cimv2.

What if you don’t know the exact service name (or display name)? This is where the LIKE WQL operator comes in handy. Just like in SQL, the ‘%’ meta character replaces any string of zero or more characters, so this query returns all Win32_Service instances where the Name property contains the string «SQL».


 *  Win32_Service 
 Name >   Name <  

WMI namespace: Root\Cimv2.

You can use all WQL operators with string properties. This query returns all Win32_Service instances whose Name is greater than ‘M’ or less than ‘O’. The usual string comparison rules apply.


 *  Win32_Service 
 ExitCode =  

WMI namespace: Root\Cimv2.

The Win32_Process.ExitCode property type is UInt32, but it is enclosed in quotes. WMI will does its best to interpret a string value and convert it to an appropriate type. This doesn’t work the other way – with string properties, you have to use quotes.


 *  Cim_DataFile 
 Drive =  
 Path =  

WMI namespace: Root\Cimv2.

Cim_DataFile is a WMI class with which you should definitely always use the WHERE clause. ‘Select * From Cim_DataFile’ alone can take hours to complete, because it will return all files on your computer. Note that the Path property doesn’t contain file names or the drive letter which is stored in the Drive property.


Associators  {Win32_NetworkAdapter.DeviceId=1} 

WMI namespace: Root\Cimv2.

  • Win32_ComputerSystem
  • Win32_DeviceMemoryAddress
  • Win32_IRQResource
  • Win32_NetworkAdapterConfiguration
  • Win32_NetworkProtocol
  • Win32_PnPEntity
  • Win32_PortResource
  • Win32_SystemDriver

Associators  {Win32_NetworkAdapter.DeviceId=1} 
 ResultClass = Win32_NetworkAdapterConfiguration 

WMI namespace: Root\Cimv2.

Most of the time, you will not need all WMI objects associated with a WMI object. You can narrow the returned collection by specifying the class of the returned objects in an Associators Of query Where clause. The above query returns an instance of Win32_NetworkAdapterConfiguration associated with the source object.


Associators  {Win32_NetworkAdapter.DeviceId=1} 
 AssocClass = Win32_NetworkAdapterSetting 

WMI namespace: Root\Cimv2.

WMI classes are associated by a special type of WMI classes, called association classes. Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration objects are associated by instances of the association class called Win32_NetworkAdapterSetting. As you can see, you can also use association class names to limit the returned object collection.


  {Win32_NetworkAdapter.DeviceId=1} 

WMI namespace: Root\Cimv2.

  • Win32_AllocatedResource
  • Win32_NetworkAdapterSetting
  • Win32_PnPDevice
  • Win32_ProtocolBinding
  • Win32_SystemDevices

Schema Queries

Schema queries are used to get information about WMI itself and its structure.


 *  Meta_Class 

WMI namespace: Any.

This is the most basic schema query. You can connect to any WMI namespace and use this query to get all the classes present in it. Meta_Class is a meta class used only in schema queries.


 *  Meta_Class 
 __Class =  

WMI namespace: Root\Cimv2.

This query uses the __Class system property to get the Win32_LogicalDisk class. Schema queries don’t return class instances, but class definitions, and a query like this will return a class definition regardless of whether there are any instances. Why would you want to get a class definition? New WMI classes are added for every new Windows version, and a query like this can check if a class exists on a system.


 *  Meta_Class 
 __Superclass   

WMI namespace: Any.

WMI is organized hierarchically – there is a hierarchy of namespaces as class containers, and there is a hierarchy of classes within each namespace. There is only one top level namespace called ‘Root’, but there is always more than one top level class in a namespace (even when you create a new empty namespace, a number of system WMI classes are created automatically). You can use this query to get all top level classes for a namespace. (This query also works if you use ‘=‘ instead of ‘Is‘.)


 *  Meta_Class 
 __Superclass =  

WMI namespace: Root\Cimv2.

For each WMI class, the __Superclass property holds the name of its immediate parent class. You can use this query to return all immediate children classes of a class. Note the quotes around the class name. __Superclass is one of the seven WMI system properties (see details here), and you can use them in schema queries. All except one – the __Dynasty property is a string array, and you can’t use array properties in WQL queries. The above query returns two classes: Win32_LocalTime and Win32_UTCTime, the immediate children of Win32_CurrentTime.


 *  Meta_Class 
 __Dynasty =  

WMI namespace: Root\Cimv2.

__Dynasty is another WMI system property – for each class, it holds the name of the top level class from which the class is derived. This query will return all children of Cim_Setting, a top level class situated in the Root\Cimv2 namespace.


 *  Meta_Class 
 __Class   

WMI namespace: Root\Cimv2.

All WMI classes belong to a schema (or at least they should). For example, classes whose name begins with ‘Cim’ belong to the Cim schema, a group of ‘core and common’ WMI classes defined by DMTF. Classes that begin with ‘Win32’ belong to the ‘Win32’ schema – these classes are derived from Cim classes and extend them. You can use this query to list all classes that belong to the ‘Win32’ schema. The query uses the Like operator – this means, it can’t be used on Windows versions earlier than Windows XP, because the Like operator was added to WQL for XP.


 *  Meta_Class 
 __This Isa  

WMI namespace: Any.

This is not an event query despite the fact that it uses the __Event class. It is a schema query that lists all child classes (both direct and indirect) of __Event. Note the use of ‘__This’, a special WMI property used in schema queries, and the ‘Isa’ operator.

This member has not yet provided a Biography. Assume it’s interesting and varied, and probably something to do with programming.

Event Queries

Event queries are used for WMI event subscriptions.

 *  __InstanceCreationEvent 
Within  
 TargetInstance Isa 

WMI namespace: Root\Cimv2.

This query is also often found in WMI samples. WMI event queries are different from other query types in that they don’t return WMI objects immediately. Instead of that, they are used for subscribing to WMI events, and objects are returned as events arrive. Note the two distinctive characteristics of event queries not present in other query types: the Within clause and the __InstanceCreationEvent class. The Within clause tells WMI how often to poll for events in seconds. In the above query, the polling interval is 5 seconds. WQL event monitoring consumes system resources, so it is important to balance between the need to get events on time and the need not to burden the system. The __InstanceCreationEvent class is one of the classes used only in event queries (other two commonly used classes are __InstanceModificationEvent and __InstanceDeletionEvent). An instance of this class is created when a requested event arrives. The __InstanceCreationEvent.TargetInstance property holds a reference to a WMI class that actually triggered the event. In the above query, it is the Win32_Process class, and we can use the TargetInstance property to access its properties.


 *  __InstanceCreationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

WMI namespace: Root\Cimv2.

This query monitors the process creation event but only for processes named ‘Notepad.exe’.


 *  __InstanceDeletionEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name =  

WMI namespace: Root\Cimv2.

Use this query to monitor process deletion events for processes whose Name property is equal to ‘Notepad.exe’. A process deletion event occurs when a process exits. There is one thing you should note about a query like this: if you open Notepad and then quickly close it (within less than 5 seconds), it is possible for WMI to miss that and not report it as an event.


 *  __InstanceModificationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name =  

WMI namespace: Root\Cimv2.

This query monitors Win32_Process modification events, not the process modification event. This is an important distinction – if the Windows process entity has a property that is not represented with a Win32_Process WMI class, and if that property changes, WMI will not report the change. Only Win32_Process property changes are returned as WMI events.


 *  __InstanceOperationEvent 
Within  
 TargetInstance Isa  
 TargetInstance.Name = 

WMI namespace: Root\Cimv2.

This query monitors all three types of events: creation, deletion, and modification events. The __InstanceOperationEvent class is the parent for the __InstanceCreation, __InstanceDeletion, and __InstanceModification classes, and you can use this fact to subscribe to all three event types at the same time. The __InstanceOperationEvent class is abstract (which means that it doesn’t have instances), so the actual event class returned by an event is one of the tree instance classes, and you can find out which one by inspecting its __Class system property. This way, you can determine the event type.


Оцените статью
Master Hi-technology
Добавить комментарий