wmi query language via powershell
Post on 06-Jul-2018
242 Views
Preview:
TRANSCRIPT
-
8/18/2019 WMI Query Language via PowerShell
1/56
viRavik
Explore
PowerS
MI
Pnth Ch
asics of W
ell can be u
Q
o ganti
I Query L
ed to retrie
er
er
nguage, di
e WMI ma
L
h
ferent types
agement in
an
ll
of WMI qu
formation u
u
eries, and le
sing WQL.
g
arn how
-
8/18/2019 WMI Query Language via PowerShell
2/56
[1]
Table
of
Contents
Introduction .................................................................................................................................................. 5
Introducing WMI Query Language ............................................................................................................ 5
WMI Query Types ..................................................................................................................................... 6
Data Queries ......................................................................................................................................... 6
Event Queries ........................................................................................................................................ 6
Schema Queries .................................................................................................................................... 7
WQL Keywords .......................................................................................................................................... 7
WQL Operators ......................................................................................................................................... 8
Tools for the job .......................................................................................................................................... 10
WBEMTEST .............................................................................................................................................. 10
WMI Administrative
Tools
......................................................................................................................
12
[WMISEARCHER] type accelerator .......................................................................................................... 14
PowerShell WMI cmdlets ........................................................................................................................ 15
WMI Data Queries ...................................................................................................................................... 16
SELECT, FROM, and WHERE .................................................................................................................... 16
Using Operators .................................................................................................................................. 17
Associators Of ......................................................................................................................................... 20
ClassDefsOnly ...................................................................................................................................... 22
AssocClass ........................................................................................................................................... 23
ResultClass .......................................................................................................................................... 23
ResultRole ........................................................................................................................................... 23
Role ..................................................................................................................................................... 27
RequiredQualifier and RequiredAssocQualifier .................................................................................. 27
References Of .......................................................................................................................................... 28
WMI Event Queries: Introduction ............................................................................................................... 30
Event Query
Types
..................................................................................................................................
32
Intrinsic Events .................................................................................................................................... 32
Extrinsic Events ................................................................................................................................... 32
Timer Events ....................................................................................................................................... 32
WQL Syntax for event queries ................................................................................................................ 33
WITHIN ................................................................................................................................................ 33
-
8/18/2019 WMI Query Language via PowerShell
3/56
[2]
GROUP................................................................................................................................................. 34
HAVING ............................................................................................................................................... 35
BY ........................................................................................................................................................ 35
Intrinsic Event Queries ................................................................................................................................ 37
__InstanceCreationEvent ........................................................................................................................ 38
__InstanceDeletionEvent ........................................................................................................................ 38
__InstanceModificationEvent ................................................................................................................. 38
Extrinsic Event Queries ............................................................................................................................... 42
Monitoring registry value change events ............................................................................................... 42
Monitoring registry key change events .................................................................................................. 43
Monitoring registry tree change events ................................................................................................. 44
Timer Events
...............................................................................................................................................
45
WMI Schema Queries ................................................................................................................................. 48
Using __this ............................................................................................................................................. 49
Using __Class........................................................................................................................................... 49
WMI Event Consumers ............................................................................................................................... 50
Temporary Event consumers .................................................................................................................. 50
Permanent Event consumers .................................................................................................................. 50
Creating an event filter ....................................................................................................................... 52
Creating a logical consumer ................................................................................................................ 52
Binding Event Filter and Consumer ..................................................................................................... 53
Introducing PowerEvents ........................................................................................................................ 53
Creating an event filter ....................................................................................................................... 54
Creating an event consumer ............................................................................................................... 54
Binding Event filter and consumer ...................................................................................................... 54
-
8/18/2019 WMI Query Language via PowerShell
4/56
[3]
This book is dedicated to Andrew Tearle, the most
passionate PowerSheller and a good friend.
Rest in peace Andy.
-
8/18/2019 WMI Query Language via PowerShell
5/56
[4]
Acknowledgements
I would like to thank Shay Levy (MVP), Philip LaVoie, and Robert Robelo for providing their
feedback. Their feedback really helped shape the ebook and include extra content that was not
planned initially. Also, thanks to everyone who read my blog posts on WMI query language and
provided feedback. Your encouragement and support helped me write quite a bit about WQL
and now this e‐book.
-
8/18/2019 WMI Query Language via PowerShell
6/56
Window
Enterpri
technoloCommo
network
Distribut
tasks on
Window
can list t #Use GeGet-Com
There ar
we shall
gets the
(disk dri Get-Wmi $_.}
In the ab
Object t
there. Y
#This eGet-Wmi
IntroThe abo
example
Let us se
Managem
e Manage
gy for
acce
Informatio
, devices, a
ed Manage
local or rem
PowerShel
ese cmdlet
t-Commandmand -Nou
five cmdle
use Get ‐W
instance(s)
es) in a sys
Object -CDriveType
ove metho
filter out
u can
use
a
xample usObject -Q
ducing e example
but a bit fa
e this in acti
nt instrum
ent (WBEM
sing manag
n Model (CI
nd other m
ent Task F
ote comput
l has a few
s by using:
and menti WMI*
ts that are u
IObject an
f a WMI cl
em,
lass Win3 -eq 3
, we retriev
hat we nee
n alternativ
s -Queryery "SELE
WMI Qses WMI Q
ter. We can
on:
ntation (W
), which is a
ment infor
M) industry
naged com
rce (DMTF
er(s).
mdlets to r
on WMI* a
sed to wor
Register ‐
ss. So, for e
2_Logical
e all instanc
. This can t
approach
parameterCT * FROM
uery Luery Langu
verify this
[5]
MI) is Micro
n industry i
mation in
a
standard to
onents. CI
. We can w
trieve the
the Noun
with WMI.
MIEvent on
xample, if
Disk | Wh
es of Win3
ake a while
y specifyin
and speci Win32_Log
nguagge to get th
sing Meas
I
soft’s imple
itiative to
enterprise
represent
is develo
ite WMI sc
anageme
However,
ly. Get‐WM
e need to li
ere-Objec
_LogicalDis
depending
‐Query
pa
fies theicalDisk
e same info
re‐Comma
tro
mentation
evelop a st
environmeystems, ap
ed and mai
ipts to auto
t data expo
ithin the sc
IObject, in i
st out all dri
t {
k and then
n how man
ameter inst
uery usinHERE Driv
rmation as
d cmdlet.
ucti
f Web Base
ndard
t. WMI
use
lications,
tained by t
mate sever
sed by WMI
ope of this
s basic usa
ves of type
ass it to W
y instances
ead of
‐clas
g WQL eType=3"
he earlier
n
d
s the
he
l
. We
ook,
e,
3
ere‐
are
.
-
8/18/2019 WMI Query Language via PowerShell
7/56
[6]
In the above example, we used three variations of Get ‐WMIObject to do the same job of
retrieving all instances of Win32_LogicalDisk where the DriveType is 3 (a disk drive). From the
output, we can see that using ‐Query and ‐Filter are the fastest ways to retrieve the WMI
information.
Note
‐Filter , as we shall see in next chapters, is a variation of ‐Query . In fact, the value of ‐
Filter represents the value of a WHERE clause when using ‐Query parameter. When
using ‐Filter , Get ‐WMIObejct cmdlet internally builds the WMI query as required.
The above example is very basic and may not really explain the usefulness of WQL — the speed
of execution is just one benefit. There are quite a few advanced querying techniques that can
be used to retrieve WMI information in an efficient manner. And, sometimes, such as working
with WMI events, WQL becomes a necessity. We shall see each of these benefits as we proceed
further.
So,
what
is
WQL?
The WMI Query Language is a subset of the American National Standards Institute Structured
Query Language (ANSI SQL)—with minor semantic changes. Similar to SQL, WQL has a set of
keywords & operators and supports three types of queries.
WMI Query Types WMI supports three types of queries:
1. Data Queries
2. Event Queries
3.
Schema
Queries
Data
Queries
This type is the simplest form of querying for WMI data and the most commonly used query
type when working with WMI. Data queries are used to retrieve class instances and data
associations. The earlier example, where we queried for all instances of Win32_LogicalDisk
where the driveType is 4, is a data query. The WQL keywords such as SELECT, ASSOCIATORS OF,
REFERENCES OF, and ISA are used in data queries.
Event Queries
The
event
queries
are
used
to
create
WMI
event
subscriptions.
For
example,
using
these
queries, we can create an event subscription to notify whenever a USB drive gets attached to
the system. The WQL keywords such as GROUP, HAVING, and WITHIN are used when creating
event queries. The event queries are critical when we want use PowerShell cmdlets such as
Register ‐WMIEvent for creating temporary event consumers. Using this cmdlet, we can create
WMI event consumers and invoke an action when the event gets triggered. We shall see more
on this in the subsequent sections.
-
8/18/2019 WMI Query Language via PowerShell
8/56
[7]
Schema
Queries
Schema queries are used to retrieve class definitions (rather than class instances) and schema
associations. In layman’s terms, these queries are used to get information about WMI and its
structure. Schema queries return a result set of class definition objects rather than actual
instances of classes. The WQL keywords such as SELECT, ASSOCIATORS OF, REFERENCES OF, and
ISA are used in schema queries and of course, in a slightly different way than how data queries use these keywords.
WMI does not support cross‐namespace queries or associations. Using WQL, we cannot query
for all instances of a specified class residing in all of the namespaces on the target computer.
Also, WQL queries are read‐only. There are no keywords such as INSERT or UPDATE. Using WQL,
we cannot modify the WMI objects.
WQL Keywords Similar to SQL, WQL queries use keywords to retrieve data from the management objects. WQL
has 19
keywords
to
perform
these
queries
against
WMI
repositories.
Even
though
there
are
19
WQL keywords, only a few of them can be used all three possible query types we discussed
earlier. The following table lists all the WQL keywords and lists the query type in which they can
be used.
Keyword Query Type Description
Data Schema Event
AND X X Combines two Boolean expressions, and returns
TRUE when both expressions are TRUE.
ASSOCIATORS OF X X Retrieves all instances that are associated with a
source instance.
Use
this
statement
with
schema
queries and data queries.
__CLASS X X References the class of the object in a query.
FROM X X X Specifies the class that contains the properties
listed in a SELECT statement. Windows
Management Instrumentation (WMI) supports
data queries from only one class at a time.
GROUP X Causes WMI to generate one notification to
represent a group of events.
HAVING X Filters the events that are received during the
grouping interval
that
is
specified
in
the
WITHIN
clause.
IS X X Comparison operator used with NOT and NULL.
The syntax for this statement is the following:
IS [NOT] NULL (where NOT is optional)
ISA X X X Operator that applies a query to the subclasses of
a specified class
-
8/18/2019 WMI Query Language via PowerShell
9/56
[8]
KEYSONLY X Used in REFERENCES OF and ASSOCIATORS OF
queries to ensure that the resulting instances are
only populated with the keys of the instances. This
reduces the overhead of the call.
LIKE X Operator that determines whether or not a given
character string
matches
a specified
pattern.
NOT X Comparison operator that use in a WQL SELECT
query
NULL X Indicates an object does not have an explicitly
assigned value. NULL is not equivalent to zero (0)
or blank.
OR X Combines two conditions. When more than one
logical operator is used in a statement, the OR
operators are evaluated after the AND operators.
REFERENCES OF X X Retrieves all association instances that refer to a
specific source
instance.
The
REFERENCES
OF
statement is similar to the ASSOCIATORS OF
statement. However, it does not retrieve endpoint
instances; it retrieves the association instances.
SELECT X X X Specifies the properties that are used in a query.
TRUE X X Boolean operator that evaluates to ‐1 (minus one).
WHERE X X X Narrows the scope of a data, event, or schema
query.
WITHIN X Specifies polling or grouping interval.
FALSE X X X Boolean operator that evaluates to 0 (zero).
We shall look at each of these keywords when we start discussing different types of WMI
queries in‐depth.
WQL Operators Similar to arithmetic operators, WQL uses the same set. The following table lists all the
operators supported in WQL.
Operator Description
= Equal to
<
Less than
> Greater than
= Greater than or
equal to
!= or Not equal to
-
8/18/2019 WMI Query Language via PowerShell
10/56
[9]
A few WQL keywords such as IS, ISA, NOT, and LIKE1 can also be considered as operators. In
these keywords, IS and IS NOT operators are valid in the WHERE clause only if the constant is
NULL.
Once again, there is a detailed discussion on how to use these operators in the upcoming
sections.
1 LIKE operator is not available in Windows 2000
-
8/18/2019 WMI Query Language via PowerShell
11/56
In the fir
keyword
available
There ar
[
P
In the su
how W
will focu
WBEWBEMT
way to e
and hen
To open
Click Sta
to what i
st chapter,
s & operato
to
execute
several to
BEMTest.e
MI tools
MISEARC
owerShell
bsequent s
I queries ca
only
on
W
TEST st.exe is pr
xplore WMI
e can do ev
WBEMTest.
t‐> Run, ty
s shown bel
e looked a
rs. Before w
WMI querie
ls that can
xe
ER] type ac
MI cmdlet
ctions, we
n be execut
MI PowerSh
sent on ev
classes and
erything yo
exe,
e “WBEMT
ow:
what is W
e dig deep i
s.
be used to
celerator in
hall look at
ed using th
ell cmdlets
ry compute
instances.
can achie
st.exe” and
[10]
L, different
n to this su
xecute WM
PowerShell
each of the
se tools. H
nd refer
to
r that has
his was init
e using W
Press Ente
Tool
types of W
ject, we sh
I queries. T
above men
wever, rest
other tools
MI installe
ially develo
I.
. This shoul
s for
MI queries,
ll look at di
is includes
ioned tools
of the chap
only when
. This tool
ed to test
d open a G
the j
and WQL
fferent tool
in detail an
ters in this
equired.
rovides a g
MI COM A
I window si
b
d see
ook
reat
PI
milar
-
8/18/2019 WMI Query Language via PowerShell
12/56
Now, we
Assumin
“Connec
actions s
WMI qu
can connec
you have
t”. Once we
uch as enu
ries. The la
t to a WMI
he necessa
are connec
erating cla
t part is wh
amespace
y permissio
ed to the r
ses, creatin
at we are in
[11]
using the “C
ns to access
ot\cimv2 n
g instances,
terested in.
onnect” bu
root\cimv2
mespace,
executing
tton at the t
namespac
e can perf
ethods, an
op.
, just click
rm several
d also exec ting
-
8/18/2019 WMI Query Language via PowerShell
13/56
In the ab
WMI qu
“Notifica
As an ex
notificati
Click on
and click
The que
expert t
WMI
WMI ad
instance
WMI obj
1.
2.
3.
ove windo
ries. The “
tion Query”
mple, we s
on queries
he “Query”
“Apply”.
y result win
ol and is a
Admininistrative
in a WMI r
ects, regist
MI CIM Stu
MI Object
MI Event r
, we can us
uery” optio
can be use
all now loo
art for
a la
button in
t
dow shows
reat tool to
strativtools can be
epository. Y
r and recei
dio
rowser
gistration
e the “Quer
n can be us
for runnin
k at how w
er part
of
t
e WBEMTe
all instance
explore W
e
Tool used to vie
ou can also
e WMI eve
[12]
” and “Not
d for WMI
WMI even
can execut
is book.
st window;
of Win32_
I interface
w and edit
use these t
ts. The free
ification Qu
Data and sc
t queries.
e simple da
enter a WQ
Process clas
.
MI classe
ols to invo
WMI tools
ery” option
hema queri
ta queries a
L statement
s. This is it.
, properties
e WMI met
download p
to execute
s. And,
nd save the
as shown
a
BEMTest i
, qualifiers
hods, mana
ackage incl
bove
s an
nd
ge
des
-
8/18/2019 WMI Query Language via PowerShell
14/56
4.
These to
http://w
f2abdc3
N
s
Once th
WMI To
In the re
another
MI Event v
ols can be d
w.micros
d314
ote
MI CIM Stu
pport exec
WMI tools
ls ‐> WMI
ulting bro
indow as
ewer
ownloaded
ft.com/dow
dio can be
uting WMI
are installe
IM Studio.
ser window
hown here:
from
nloads/en/
sed to exec
vent querie
, open WM
his prompt
, click on
[13]
etails.aspx
ute data/sc
s.
I CIM studi
for the W
icon at th
FamilyID=6
hema queri
by selectin
I namespa
e top‐right
430f853‐11
s. WMI To
g Start ‐> Al
ce selection
orner. This
20‐48db‐8c
ls do not
l Programs ‐
and creden
brings up
5‐
>
tials.
-
8/18/2019 WMI Query Language via PowerShell
15/56
Type ‘Sel
This sho
using CI
queries.
[WMWindow
shortcut
manage
[WMI]
[WMICL
[WMISE
Within t
can be u
[WMISE
namesp
1. P
2. I
2 Manage
ect * from
s all the in
Studio. Th
hese tools
SEARC PowerShel
are called
ent names
WMI ty
SS]
RCHER]
e scope of
ed to run
RCHER] is
ce. The wa
rovide a W
voke the G
entObjectSea
in32_Proc
tances of
e WMI tool
are also a g
HER] t l provides s
ype acceler
paces. Thes
e accelerat
his book, w
MI queries
shortcut fo
we use thi
L statemen
t() method
cher Class - h
ss’ (withou
in32_Proce
are used f
eat way to
pe accortcuts to
ators. Ther
e are,
or
e are more
.
r System.M
type accel
t.
to execute
ttp://msdn.mic
[14]
t quotes) in
ss class. Si
r many oth
explore and
leratollow direct
are three t
Retrie
Access
WMI c
Search
interested i
nagement.
rator is:
the WMI qu
rosoft.com/en
the query t
ilarly, we c
er purposes
learn abou
r access to .
ype acceler
e single ins
static prop
lass.
for WMI o
how [WM
Manageme
ery.
us/library/z0z
xtbox and
n execute s
than just e
WMI.
ET namesp
tors to acc
escription
tance of a
erties and
jects
ISEARCHER]
tObjectSea
x1aya.aspx
lick “Execu
chema que
ecuting W
ces. These
ss WMI
MI class.
ethods of a
type accele
rcher2 .NET
e”.
ies
I
rator
-
8/18/2019 WMI Query Language via PowerShell
16/56
[15]
Simple. And, this is how we use it at the PowerShell console.
$svcs = [WmiSearcher]"Select * from Win32_Service where State='Running'" $svcs.Get()
In the above code snippet, we are using the [WMISEARCHER] shortcut to get a list of all services
in “running”
state.
By
default,
the
scope
of
the
query
is
set
to
root\cimv2
namespace.
In
case
you want to change the scope to a different namespace, you can do so by setting the “scope”
property of this object. For example,
$objSearch = [WmiSearcher]"Select * from MSPower_DeviceEnable" $objSearch.Scope = "root\WMI" $objSearch.Get()
In this above example, we change the scope to root\WMI namespace to retrieve all the
instances of MSPower_DeviceEnable class. Using this type accelerator, we can set some
extended properties3 such as blocksize, timeout, etc. These options are not available in the
built‐in
WMI
cmdlets
method.
We can use [WMISEARCHER] for some quick access to WMI information but it gets quite
verbose soon. This brings us to the last section of this chapter – using PowerShell WMI cmdlets
to execute WMI queries.
PowerShell WMI cmdlets As mentioned in the first chapter, PowerShell v2.0 includes five WMI cmdlets. Within these five
cmdlets, Get ‐WMIObject and Register ‐WMIEvent can be used to execute WMI Queries. Get ‐
WMIObject can be used for data/schema queries while Register ‐WMIEvent can be used for
triggering
event
queries.
We have seen several examples using Get‐WMIObject already. So, here is a quick example of an
event query using Register ‐WMIEvent .
Register-WmiEvent -Query "Select * from __InstanceCreationEvent WITHIN 10WHERE TargetInstance ISA 'Win32_Process'" -Action {Write-Host "New processcreated"}
The above query will display a message, “New Process Created”, every time a new process gets
created on the system. Don’t worry much even if you don’t understand anything here. WMI
event queries require a complete discussion and we shall see that in the later chapters.
There are several other tools to execute WMI Queries or access WMI information in general.
This list includes Sapien WMI Browser4, MoW’s WMI Explorer PowerShell script, etc. Go,
explore!
3 [WMISEARCHER] Query options: http://msdn.microsoft.com/en-
us/library/system.management.enumerationoptions.aspx 4 Sapien’s WMI browser - http://www.sapien.com/
-
8/18/2019 WMI Query Language via PowerShell
17/56
[16]
WMI Data Queries
WMI data queries are the simplest form of querying for WMI data. WMI data queries are used
to retrieve class instances and associations. There are several keywords and operators that are
used in
WMI
data
queries.
This
includes
keywords
such
as
SELECT,
FROM,
WHERE,
Associators
Of, References Of, NOT, LIKE, IS, NULL, and all other operators we saw in chapter one.
In this chapter, we shall start looking at the most commonly used form of data queries and then
move on to data queries for association. As a part of the examples, we shall look at how some
of the operators are used, gotchas when using operators, and finally how to use multiple
operators in a query.
SELECT, FROM, and WHERE The general syntax when using SELECT keyword for data queries is:
SELECT [* | Property Names] FROM CLASSNAME
So, if you want to get all instances of Win32_Service class and all properties,
$query = "SELECT * FROM Win32_Service" Get-WmiObject -Query $query
This will list all instances of Win32_Service and properties of each instance.
Note
Remember that
you
can
perform
data
queries
only
from
one
class
at
a time.
For
example, the following query will produce an invalid query error: Get-WmiObject -Query "Select * from win32_Service, Win32_Process"
What if we want to limit the instances to one particular service? Let us say AudioSrv. We can
use WHERE clause to filter that. Here is how we do it:
$query = "SELECT * FROM Win32_Service WHERE Name='AudioSrv'" Get-WmiObject -Query $query
This will list only one instance and the properties of that instance. WHERE is used to narrow the
scope of retrieved data. This keyword can be used in all of the three query types. In general,
WHERE clause when used with SELECT statement can take one of the following forms:
SELECT * FROM class WHERE property operator constant
SELECT * FROM class WHERE constant operator property
-
8/18/2019 WMI Query Language via PowerShell
18/56
[17]
In the above two forms, property denotes a valid property of a WMI instance, operator is any
valid WQL operator and constant must be of the correct type for the property. Let us look at an
example for the second form of using WHERE.
$query = "SELECT Name, State FROM Win32_Service WHERE 'AudioSrv' LIKE Name" Get-WmiObject -Query $query
In the above example, we replaced ‘*’ with Name & State to limit the number of properties in
the output. This query, when executed, gets us an instance of Win32_Service with name
‘audiosrv’ and lists only the name and state properties of the service. By doing so, we are
reducing the bandwidth required to execute the query and the amount of data we get in return.
Note
The above query results in listing the system properties such as __PATH, etc in the
output. This is because the default formatting for the WMI class is lost when we specify
a selected set of properties.
Using
Operators
In this section, we shall look at different operators that can be used with WMI data queries and
how we can use them.
LIKE
In the preceding example, we filtered out the instances by using WHERE clause and specifying
that we need only one instance of Win32_Service. What if we don’t know the exact service
name but we know that it has the word audio in it.
$query = "SELECT * FROM Win32_Service WHERE Name LIKE '%Audio%'"
Get-WmiObject -Query $query
This will list all the services that have the word ‘audio’ in the name of the service.
Note
You can use ‐Filter parameter instead of a WHERE clause or even ‐query . When using ‐
filter , Get ‐WMIObject cmdlet builds the required WQL statement internally. For example: Get-WmiObject -Class Win32_Service -Filter {Name='AudioSrv'}
This is just a preference and in the scope of this book, I will use ‐query only.
Observe carefully how we used the keyword like and wrapped the word audio between %%.
We have
known,
probably
since
the
DOS
days
that
‘*’
is
the
wild
card
character
for
specifying
something like “get anything that has the word”. However, in WQL, ‘%’ is the wild card
character when using LIKE keyword. There are also other meta characters such as [ ], ^, and _
that we can use with LIKE operator.
Here are some examples of how we use these additional meta characters.
$query = "SELECT * FROM Win32_Service WHERE Name LIKE '[af]%'"
-
8/18/2019 WMI Query Language via PowerShell
19/56
[18]
Get-WmiObject -Query $query
The above query gets us all services with a name that starts with ‘a’ or ‘f’. The way we use ‘[ ]’ is
very similar to its usage in regular expressions. This is used to specify a range of characters.
In
case
you
need
all
services
that
start
with
any
letter
from
‘a’
to
‘f’,
we
still
use
‘[
]’
meta
character but specify the range. Here is how we do it:
$query = "SELECT * FROM Win32_Service WHERE Name LIKE '[a=f]%'" Get-WmiObject -Query $query
Note
You can either use ‘[a=f]%’ or ‘[a‐f]%’ in the above query. Although, MSDN
documentation specifies only ‘=’; the ‘‐‘ character has the same meaning.
Let us look at another meta character, ‘^’.
$query = "SELECT * FROM Win32_Service WHERE Name LIKE '[^afgh]%'" Get-WmiObject -Query $query
The above query gets us only the services with a name that does not start with ‘a’ or ‘f’ or ‘g’ or
‘h’. In the above query, by using ‘^’, we specify that we want to list all the services with names
not starting with the characters in the range.
The last meta character is ‘_’ and this indicates any one character similar to ‘?’ in DOS. Here is
how we use it.
$query = "SELECT * FROM Win32_Service WHERE Name LIKE '%a_diosrv%'"
Get-WmiObject -Query $query
What we are trying in the above query is obvious. The ‘_’ gets replaced by any character and
the matching service will be listed in the output.
AND, OR, and NOT
We can test for multiple conditions inside the WHERE clause. Let us see how we can do that.
For example, if we want to list all services in the ‘running’ state but the StartMode set to
‘manual’
$query = "Select * from Win32_Service Where State='Running' AND
StartMode='Manual'" Get-WMIObject -Query $query
Simple! By using AND, we specify that we need both conditions to evaluate to TRUE. What if we
want to list all services that are in ‘running’ state and StartMode set to ‘manual’ and the service
name starts with the characters ‘a’ or ‘f’. We have seen the first part of this query already. From
the description of the problem, we know that we need to use another AND operator. Here is
how the query will look like:
-
8/18/2019 WMI Query Language via PowerShell
20/56
[19]
$query = "Select * from Win32_ServiceWhere (State='Running' AND StartMode='Manual')AND (Name LIKE '[af]%')"
Get-WMIObject -Query $query
See how we did that. Enclosing the conditions in parentheses is not very important, at least in
this query. But, this is a good practice to express a query like that. In the later sections, we will
see
where
using
parentheses
is
necessary.
Now, let us look at OR operator. By using OR, we specify that we want to get a list of instances
whenever one of more conditions evaluate to TRUE. Let us see an example:
$query = "Select * from Win32_Service Where State='Stopped' ORState='Paused'" Get-WMIObject -Query $query
In this preceding example, we are retrieving all instances of Win32_Service where the service
state is either ‘stopped’ or ‘paused’. Now, let us make it a bit more complex by adding one
more condition. Let us get a list of all services that are either in ‘running’ or ‘paused’ state AND
with name
that
starts
with
either
‘a’
or
‘f’.
If
the
problem
description
is
not
clear,
read
it
again.
Now, run the below query and see what you get in the output.
$query = "Select * from Win32_Service Where State='Running' OR State='Paused'AND Name LIKE '[af]%'" Get-WMIObject -Query $query
So, what was there in output? All instances of running services irrespective of the service name
condition we wanted to check. Why did that happen? Because, when using OR, it is just enough
to evaluate any one condition to TRUE. So, whenever service state was ‘running’, this query
returned the instance of the class. It did not really bother to look at other conditions. How do
we make this work to get only what we want?
Here is how we do it:
$query = "Select * from Win32_Service Where (State='Running' ORState='Paused') AND Name LIKE '[af]%'" Get-WMIObject -Query $query
See how we combined the first two conditions. This is where parentheses are useful.
Let us now see how we can use NOT operator. Here is a very simple example and probably does
not require any explanation.
$query = "Select * from Win32_Service Where NOT (State='Running')" Get-WMIObject -Query $query
The same thing can be expressed using the other operators such as ‘’ and ‘!=’ also.
$query = "Select * from Win32_Service Where State'Running'" Get-WMIObject -Query $query
$query = "Select * from Win32_Service Where State!='Running'"
-
8/18/2019 WMI Query Language via PowerShell
21/56
[20]
Get-WMIObject -Query $query
All three preceding examples have the same meaning. They are just more than one way to get
the same result.
IS, IS NOT and NULL
You can also use IS, IS NOT operators within WHERE clause. However, the query will be valid
only if the constant is NULL. For example, the following query
$query = "SELECT * FROM Win32_LogicalDisk WHERE FileSystem IS NULL" Get-WMIObject -query $query
…is valid and returns the disk drive information with no file system information. On my system,
this query returns the DVD drive information.
Note
Some properties of the WMI classes may not be displayed when using default output
formatting. For
example,
when
we
just
query
using
“Select
* From
Win32_LogicalDisk”,
we won’t see FileSystem property. To see all the properties, you need to pipe the
output of Get ‐WMIObject cmdlet to Format‐List *.
The following example,
$query = "SELECT * FROM Win32_LogicalDisk WHERE DriveType IS 5" Get-WMIObject -query $query
…will result in an invalid query error since the constant we specified is not NULL.
Using the IS NOT operator combination is similar to the first example using the IS operator.
$query = "SELECT * FROM Win32_LogicalDisk WHERE FileSystem IS NOT NULL" Get-WMIObject -query $query
Associators Of As we saw in the previous section, SELECT queries can be used to retrieve instances of a WMI
class. But SELECT queries are not the only way to query for instances. We can also use the
‘Associators Of’ keyword to do the same. However, there is a difference. SELECT queries always
return a collection of instances of a WMI class where as “Associators Of” returns a collection of
WMI objects that belong to different WMI classes or associated WMI classes. Before we dig too
much in to this, let us first understand, what are these associated WMI classes?
Take an example of a Windows service. WMI has several classes that represent windows service
information. Let us look at Win32_Service and explore how this class is associated with other
classes in WMI. We shall use CIM Studio for this purpose. To see this,
Open CIM Studio from WMI Tools.
Connect to root\cimv2 namespace.
-
8/18/2019 WMI Query Language via PowerShell
22/56
D
I
N
The belo
class na
Win32_S
The Netl
another
Win32_L
In the ab
of Win3
Win32_
endpoin
Now, usi
a particu
Note tha
Let us lo
$query Get-Wmi
The abo
curly bra
this can
Name=’
case – sh
properti
ouble‐click o
the results
ow, select th
w screen ca
e that rela
ystemServi
ogon servic
association
oadOrderG
ove exampl
_Computer
oadOrderG
s.
ng the “Ref
lar source i
t the brace
k at an exa
= "AssociObject -Q
e snippet
s
ces. This qu
ake a while
etLogon’ w
ould be the
s list in W
n Win32_Ser
indow, righ
e “Associatio
pture show
es Win32_S
es, is called
depends o
class Win32
oupService
e, Win32_S
System, Wi
oup.Name=
rences Of”
stance. Her
are part of
mple to und
tors of {ery $quer
ows the
ba
ery — when
and the ou
ill not retur
“key”. You
I CIM Studi
ice class; ret
‐click on “Ne
ns” Tab.
the associ
ervice to W
an associati
n LanmanW
Dependen
embers – r
rvice.Name
32_Service
”MS_Wind
keyword, w
e is the gen
ASSOCIATO
the syntax.
erstand thi
in32_Sery
sic usage
of
executed
put can be
anything.
an identify
. This prop
[21]
rieve all inst
tlogon” insta
tions. If we
n32_Comp
on class.
orkstation s
Service. An
elates a loa
=”NetLogo
.Name=”La
wsRemote
e can retrie
eral syntax
RS OF {Obj
ny valid o
.
ice.Name=
‘Associator gets all th
verwhelmi
his is requi
the proper
erty uniquel
nces by clic
nce and sele
mouse‐ove
terSystem.
ervice. This
, finally, a t
d order gro
” is the sou
manWorks
alidation”
e all instan
f this keyw
ctPath}
ject path c
'NetLogon'
Of’.
Make
instances
ng. Remem
red and the
y that is de
y identifies
ing on ic
ct “Go to Obj
r the ic
This class,
relation is i
hird associa
p and a ba
rce instanc
ation”, and
are the targ
ces that are
ord:
n be used f
'}"
a note
of
th
f all associ
er, this qu
property – ‘
ignated as
the WMI cl
n.
ect”.
n, we can s
dicated by
tion class –
e service.
while insta
t instances
associated
r ObjectPa
e syntax
insi
ted classes.
ry without
Name’ in th
ey by looki
ss instance.
ee a
nces
or
ith
h.
de
So,
is
g at
-
8/18/2019 WMI Query Language via PowerShell
23/56
Look at t
Similar t
clause. H
SELECT q
ASSOCIA
AssocCla
ClassDef
RequireRequire
ResultCl
ResultRo
Role = P
N
Y
s
Let us se
ClassD
Let us fir
You can
$query Get-WMI
As we se
Studio o
he ico
the data q
owever, th
ueries. The
TORS OF {O
ss = AssocCl
sOnly
AssocQualiQualifier =
ss = ClassN
le = Proper
opertyNam
ote
ou cannot u
hile using A
parating th
e the exam
fsOnly
st see a wa
se the key
= "AssociObject -Q
e, the list o
tput.
next to th
ueries using
usage of
e are prede
bjectPath}
assName
ier = Qualifi
ualifierNa
me
yName
e
se logical o
ssociators
em by a spa
les around
to list only
ord ClassD
tors Of {ery $quer
associated
property ‘
SELECT key
HERE claus
fined keyw
HERE
erName
e
erators suc
f keyword.
ce.
how to use
the associa
efsOnly for
in32_Sery
class names
[22]
ame’. This
word, the a
is a bit dif
rds that yo
h as AND, O
You can use
these keyw
ed class na
his purpos
ice.Name=
we see her
identifies t
ssociation q
erent from
can use wi
R, and NOT
more than
rds within
es as sho
.
'NetLogon
e is same as
e key prop
ueries can a
how you do
th WHERE c
within the
one keywor
HERE clau
n in the scr
} WHERE C
what we sa
rty.
lso use WH
that with
lause. They
HERE clau
d by just
se.
enshot ab
lassDefsO
w in the CI
RE
are:
e
ve.
ly"
-
8/18/2019 WMI Query Language via PowerShell
24/56
AssocCl
The Ass
source t
instance
$query AssocClGet-Wmi
This que
associati
ResultC
This key
specified
$query ResultCGet-WMI
Result
The
Restheir ass
For a mo
services
parsing
same by:
$query ResultRGet-WMI
The abo
is similar
Get-Ser
Similarly
ass
cClass key
rough the
of associat
= "Associass=Win32Object -Q
y gets us th
on class. Thi
lass
ord indicat
ResultClas
= "Associlass=Win3Object -Q
ole
ltRole
keyciation wit
ment think
that depen
in32_Dep
= "Associole=DepenObject -Q
e query
wil
to:
vice -Nam
to get a lis
ord indicat
pecified cla
d class thou
tors of {Dependentery $quer
e end point
s is shown i
es that you
. For examp
tors Of {_LoadOrdeery $quer
ord
indicat the sourc
that Get‐Se
on a specif
ndentServi
tors of {ent" ery $quer
list
all
the
"LanmanW
of services
s that the r
s or one of
gh a single
in32_SerService" y
instance as
the below
want to ret
le,
in32_SerrGroup" y
s
that
the
r object.
vice cmdlet
ic service wi
e instances
in32_Ser
y
ervices tha
orkstatio
that a speci
[23]
turned en
its derived
ssociation
ice.Name=
ociated thr
screen cap
ieve the en
ice.Name=
turned
end
never exist
thout using
. However,
ice.Name=
depend
on
" -Depend
fic service d
points mus
lasses. If y
class:
'NetLogon'
ough Win3
ure.
d points ass
'NetLogon
points
mus
ed. Now, if
“Associator
sing ‘Assoc
'LanmanWo
LanmanWo
entServic
epends on:
t be associa
u want to r
'} WHERE
_Dependen
ociated onl
} WHERE
t
play
a
part
ou want to
s Of”, we w
iators Of’,
kstation'
rkstation se
s
ed with the
trieve the
tService
with the
icular
role
i
get a list of
ould do tha
e can do th
} Where
rvice. And,
by
e
his
-
8/18/2019 WMI Query Language via PowerShell
25/56
[24]
$query = "Associators of {Win32_Service.Name='NetLogon'} WhereResultRole=Antecedent" Get-WMIObject -Query $query
This example will list LanmanWorkstation as NetLogon service depends on this service to start.
And, this is similar to running:
Get-Service -Name "Netlogon" -RequiredServices
So, what are these dependent and antecedent roles we used in the above queries? Let us
slow down a bit and understand the WMI relationships.
We can classify WMI relationships in‐to three basic types:
Dependency relationship
Element‐Setting relationship
Component relationship
On a related
note,
MSDN
documentation
for
several
WMI
classes
lists
properties
such
as
Dependent, antecedent, Element, setting, Group Component, and part component. We shall
explore the meaning of these in the coming sections.
Dependency Relationship
This relationship defines an association where one object is dependent on another object –
antecedent . The association class we just used – Win32_DependentService – is a classic
example. This class defines a dependency relationship between two Windows services. From
the above examples, the Win32_Service.Name=”NetLogon” is dependent on
Win32_Service.Name=”LanmanWorkstation” – which is the antecedent. Now, go back to the
examples and
read
them
again.
Another example is the Win32_DiskDriveToDiskPartition association class. This class relates
Win32_DiskDrive and Win32_DiskPartition classes where Win32_DiskDrive plays the
antecedent and Win32_DiskPartition plays the dependent role. In simple English, a partition is
dependent on a disk drive and by specifying one of these roles – dependent or antecedent; we
can get either class instances – Win32_DiskDrive or Win32_DiskPartition, respectively.
So, if we want to query for all disk partitions on a specific hard drive:
$query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='\\.\PHYSICALDRIVE0'}
WHERE ResultRole=Dependent" Get-WmiObject -Query $query
Here is what I see on my system:
-
8/18/2019 WMI Query Language via PowerShell
26/56
Elemen
This rela
– and th
and Setti
screen c
Win32_
Win32_
Win32_
How do
informat
$query ResultRGet-Wmi
Similarly
adapter
N
Is
y
$query ResultRGet-Wmi
‐Setting R
ionship def
settings fo
ng. For exa
pture from
etworkAda
etworkAda
etworkAda
e use this
ion by usin
= "Associole=ElemeObject -Q
by queryin
onfiguratio
ote
the above
stem. Use
our networ
= "Associole=SettiObject -Q
lationship
ines the ass
r that elem
ple, take a
CIM studio
terSetting
ter and Wi
ter is the E
Let us look
the followi
tors Of {t" ery $quer
g Win32_N
n informati
query, I use
et‐WMIOb
adapters.
tors Of {g" ery $quer
ciation bet
nt. These a
look at Win
shows the t
ssociation
32_Netwo
lement and
at a few ex
g query:
in32_Net
y
tworkAdap
n.
d network
a
ect –Class
in32_Net
y
[25]
ween an el
sociation cl
32_Networ
o properti
lass define
kAdapterC
Win32_Net
amples. We
orkAdapte
er class an
dapter inde
in32_Net
orkAdapte
ment – for
asses have
AdapterSe
es of this as
a relations
nfiguration
workAdapt
can retriev
rConfigur
for ‘settin
x 12.
This
m
ork adapte
r.DeviceI
example a n
properties n
ting class.
sociation cl
hip betwee
classes. In t
rConfigura
the netwo
tion.Inde
’ role, we g
ay or
may
n
r to find the
=12} Wher
etwork ada
amed Elem
he followin
ss.
his relation
ion is the s
rk adapter
x=12} Whe
t the netw
ot exist
on
index value
e
pter
nt
hip,
tting.
e
rk
our
for
-
8/18/2019 WMI Query Language via PowerShell
27/56
Compo
This WM
Let us un
associat
Win32_
the grou
Let us se
We can
$query WHERE RGet-Wmi
In the
ab
we used
key prop
the prop
either a
We wer
details.
output.
Similarly
$query WHERE RGet-Wmi
ent relati
I relationshi
derstand th
s Win32_G
roupUser d
p.
e a few exa
et a list
of
= "AssociesultRoleObject -Q
ove query,
both Name
erties in Wi
erties is not
omain na
also limitin
therwise,
if
we
want
= "AssociesultRoleObject -Q
nship
p contains t
is with the
oup (Group
efines a rela
ples now.
roup memb
tors Of {GroupCompery $quer
e list
all
th
and Domai
32_Accoun
specified. A
e or the loc
g the Result
e may end
to
get
a
list
tors OfPartCompoery $quer
wo or more
elp of an e
Component
tionship be
erships for
in32_Acconent Resy | Selec
groups
in
properties
t WMI class
lso, make a
al compute
Class to Wi
up seeing c
of
all
users
i
Win32_Accnent Resuly | Selec
[26]
classes as
ample. The
) and Win3
ween a gro
ny given
u
unt.Name=ltClass=W Name
hich Dem
. This is req
. We will ge
note that t
name.
32_Accoun
mputer sys
n
a
group:
ount.NametClass=Wi Name
roupComp
Win32_Gr
_Account (
up and an a
er account
'DemoUserin32_Acco
User1 is
a
ired as bot
t an invalid
e value of
t . This help
tem details
'DemoGroun32_Accou
nent and P
upUser W
PartCompo
ccount that
using the
fo
',Domain=nt"
ember. In
these pro
object path
omain pro
us in gettin
also as a pa
p2',Domait"
artCompon
I class
ent) classe
is a membe
llowing que
'DomainNa
he object
p
erties are t
error if one
erty can be
g only the g
t of the qu
='DomainN
nt.
.
r of
ry:
e'}
ath,
e
of
roup
ry
ame'}
-
8/18/2019 WMI Query Language via PowerShell
28/56
As show
part of D
That is a
Associat
Role
The Role
source o
The diffe
keyword
source i
associati
Now, let
to list all
$query WHERE RGet-Wmi
The resu
observe
queried
GroupCo
Requi
There ar
R
T
a
s
WMI qu
indicatio
in
the
scre
emoGroup
out WMI r
ors Of keyw
keyword in
bject where
rence betw
, we indicat
stance. Wh
on where t
us see som
members o
= "Associole=GroupObject -Q
lt of both th
the differen
or all insta
mponent.
edQualif
other key
equiredQu
ith the sou
he Require
ssociated w
ecified qua
lifiers are v
ns, method
en capture
.
lationships.
ord.
dicates that
the source
en this
key
that the e
en using Rol
e source o
examples
f a given gr
tors Ofomponentery $quer
ese queries
ce between
ces of Win3
ier and R
ords such
lifier keyw
ce object th
AssocQuali
ith the sour
lifier.
alues that p
, method p
bove, by
e
Let us mov
the returne
object plays
word and
R
dpoint mu
e keyword ‐
ject plays a
o understa
up to:
Win32_AccResultClay | Selec
is same. Th
two querie
2_Account.
equired
s Required
rd indicate
rough an as
fier keywor
e object th
ovide addit
rameters, t
[27]
ecuting the
e on to oth
d endpoint
a particula
sultRole ke
st a play a p
‐ we specif
particular
d this. We
ount.Names=Win32_A Name
y just list al
. In the sec
Name=’De
ssocQua
ualifier an
that the re
sociation cl
indicates t
ough an as
ional infor
riggers, inst
query, we
r interestin
participate
role.
yword is:
w
articular ro
that the en
ole.
can just twe
'DemoGrouccount"
l members
nd variatio
oGroup2’
ifier
RequireAs
turned end
ss that incl
hat the ret
ociation cl
ation abou
ances, prop
ee a list
of
g aspects o
in an assoc
hen using
R
le in associ
dpoints par
ak the quer
p2',Domai
of DemoGr
n, using Rol
here Win3
socQualifier
oints must
udes the sp
rned endp
ss that incl
classes, as
erties, or re
ll users
wh
using
iation with
sultRole
tion with t
ticipate in a
that we u
='DomainN
up2. Howe
keyword,
_Account i
.
be associat
cified quali
ints must b
des the
ociations,
ferences. T
are
he
e
n
ed
ame'}
er,
e
a
d
fier.
ese
-
8/18/2019 WMI Query Language via PowerShell
29/56
qualifier
discussi
This brin
final key
RefeThis key
REFERE
REFERE
Howeve
instance
In the ab
and Win
“Referen
using “A
Win32_
keyword
$query Get-Wmi
$query Get-Wmi
5 WMI Sta
5 can be us
n of these t
gs us to the
ord used i
ences ord retriev
CES OF stat
CES OF {Ob
, rather tha
. Let us re‐
ove screen
2_LoadOr ces Of” key
sociators O
omputerSy
s side by sid
= "RefereObject -Q
= "AssociObject -Q
ndard Qualifi
d to narro
o keyword
end of disc
WMI data
f es all associ
ement is si
ect Path}
n retrieving
isit an earli
capture fro
erGroupSer ord alone,
f” keyword,
tem, Win32
e in an exa
ces Of {Wery $quer
tors Of {ery $quer
rs: http://msd
the result
s here.
ssion on “A
queries.
ation instan
ilar to the
endpoint in
r example
CIM Studi
iceMembewe retrieve
we retrieve
_Service, an
ple:
in32_Serviy
in32_Sery
.microsoft.co
[28]
set from th
ssociators
ces that ref
SSOCIATO
stances, it r
o understa
o, Win32_S
s are
the
as
the instanc
the instanc
d Win32_L
ce.Name='
ice.Name=
/en-us/librar
WMI quer
f” keyword
r to a parti
S OF state
trieves the
d this.
stemServic
sociation cl
es of these
es of end p
adOrderGr
Netlogon'
'Netlogon'
/aa393651(v=
. There is n
. Let us now
ular source
ent in its s
intervening
es, Win32_
sses. When
association
ints –
up. Let us s
Where Cl
'} Where C
vs.85).aspx
o in‐depth
move on t
instance. T
ntax.
association
ependentS
using
classes whe
ee both
assDefsOnl
lassDefsO
the
e
rvice,
reas
y"
ly"
-
8/18/2019 WMI Query Language via PowerShell
30/56
You see
output a
Similar t
keyword
syntax f
REFERE
ClassDef
Require
ResultCl
Role = P
The usag
This con
in this ch
event qu
he differen
nd this
help
Associator
also. There
r using WH
CES OF {Ob
sOnly
Qualifier =
ss = ClassN
opertyNam
e of these k
ludes this c
apter. In th
eries.
e. By using
s us
underst
s Of keywor
are predefi
RE clause i
ectPath} W
ualifierNa
me
e
eywords is
hapter on
next chap
the ClassDe
and the
dif
d, you can
ed keywor
:
HERE
e
imilar to “A
MI data qu
er, we shall
[29]
fsOnly key
erence.
se the WH
s that you
ssociators
eries. We lo
look at ho
ord, we li
RE clause
an use wit
f”.
oked at sev
to use W
it the verb
ith “Refere
WHERE cla
eral keywor
I query lan
sity of the
ces Of”
use. The ge
s and oper
uage for W
neral
ators
MI
-
8/18/2019 WMI Query Language via PowerShell
31/56
Just as t
using W
can be
A WMI e
Window
There ar
paramet
specify a
a WMI e
So, from
do we fi
#Get al#filterGet-WMIAND (__
This will
remove
Win32_
PowerSh
class to
RegisteStarted
N
‐
t
r
6 Event Co
W
ere is a W
I, there is
onitored b
vent occurs
PowerShel
a couple o
ers to creat
WMI event
ent class?
the above
d what are
l classesclass na
Object -QClass lik
list all WMI
he second
rocessStart
ell comman
ubscribe to
r-WmiEven" -Action
}
ote
ction para
e event ge
ceive the e
nsumers: http:
MI E
I class that
WMI class
WMI occur
when that i
l v2 provide
f different
a tempora
class. So, w
es, PowerS
rror, we un
the WMI ev
that arees for Wiery "Sele 'win32%'
event class
ondition in
race is one
d. This class
all process
-Class W {Write-Hojust sta
eter can b
s fired. Alte
ents.
//msdn.micros
ent
represents
that repres
s, an
instan
nstance is c
s a cmdlet
ays we can
ry6 event co
hat happen
ell complai
erstand th
ent classes?
MI eventn32 classct * from)"
s that start
the WHERE
of the WMI
indicates t
tart events.
in32_Proc
st "$($Everted"
used to sp
rnatively, y
oft.com/en-us/
[30]
uer
ach type o
nts each ty
e of
the
co
eated.
Register ‐
use this cm
nsumer. W
if the valu
ns about it.
t Win32_P
classes s meta_clas
with Win32
clause but
event class
e new proc
For exampl
ssStartTr
nt.Source
cify the scr
u can use
library/aa393
es: I
system res
pe of WMI
responding
MIEvent –
dlet. You ca
en using ‐C
provided t
ocess isn’t
s Where (
prefix. We
or starters,
es listed wh
ess started
le,
ace -Sour
EventArgs.
iptblock us
ait ‐Event a
13(VS.85).as
tro
ource that c
vent. Whe
WMI
event
to consume
n either use
lass parame
o the ‐Class
WMI even
_This ISA
ill see man
this is good
en we exec
vent. We c
eIdentifi
NewEvent.
d to take s
nd Get ‐Eve
x#event_con
ucti
an be mana
an event t
class
is
cre
WMI even
‐Class or ‐
ter, we nee
parameter i
t class. But,
'__Event
y more if w
enough.
te the abo
an use this
er "Proce
ProcessNa
me action
t cmdlets t
umers
n
ged
at
ted.
s.
uery
d to
sn’t
how
)
e
e
MI
s
e)
hen
-
8/18/2019 WMI Query Language via PowerShell
32/56
N
Y
d
This com
process
process
So, what
unneces
receive t
this exa
#RegistRegisteProcess
}
NIt
t
The WQ
narrow
There ar
just saw
In the ea
ote
ou have to
enied mess
mand will r
ame.
Howtarts and n
if we are in
ary proces
he event w
ple:
er-WMIEver-WmiEvenName='not
ote
is possible
e ‐comput
L statemen
own the ev
many oth
is one way
rlier section
pen the Po
ge every ti
gister an e
ver, this
wi
t just the o
terested onl
es before di
en we don’
t using - -Query "pad.exe'"
Wr
o register f
rName par
we used
ents to just
r ways to m
f doing it.
, we saw ho
erShell co
e we try u
ent consu
ll result
in
r
ne we are i
y in one sp
splaying th
t need it? T
Query Select *-Action
ite-Host "
r a remote
meter. This
hould be f
he ones we
onitor proc
e shall see
w to list W
[31]
sole in ele
ing Registe
er and disp
ceiving the
terested in.
cific proces
process na
is is where
rom Win32 New notep
WMI event
book, how
miliar to y
need.
ess creation
the other
I event cla
ated mode.
‐WMIEvent
lay a messa
messages
s? We coul
me at the c
‐Query par
_ProcessS
ad proces
using Regis
ver, looks
ou by now.
using WMI
ethods in t
ses and ho
Else, we wi
.
ge with the
t the
consol
have easil
nsole. But,
meter com
artTrace
created"
ter ‐WMIEve
t the local
This query
events and
e later sect
to use Re
ll see an acc
newly creat
e every
tim
filtered ou
why even
s handy. L
WHERE
nt cmdlet a
MI events
can be us
WQL. What
ions.
ister ‐WMI
ess
ed
e any
the
ok at
d
only.
d to
we
vent
-
8/18/2019 WMI Query Language via PowerShell
33/56
[32]
to subscribe to the events from that WMI class. In the case of a WMI event class, the class itself
provides the events. Hence, we can use the class name directly and create an event subscriber.
In the case of non‐event classes, WMI does all the hard lifting of monitoring the class instances
and providing whenever an instance is created, modified, or deleted. Now, how do we
subscribe to
the
events
from
these
non
‐event
classes?
This
question
brings
us
to
the
discussion
on types of event queries.
Event Query Types There are three types of event queries in WMI: intrinsic events, extrinsic events, and timer
events. Here is a brief discussion on each of these event types:
Intrinsic
Events
Intrinsic events are used to monitor a resource represented by a class in the CIM repository. In
other words, the intrinsic events occur in response to a change in the standard WMI data model.
WMI creates
intrinsic
events
for
objects
stored
in
the
WMI
repository.
A
provider
generates
intrinsic events for dynamic classes, but WMI can create an instance for a dynamic class if no
provider is available. WMI uses polling to detect the changes. There are many system classes
that WMI uses to report intrinsic events. However, the ones that are most interesting and
useful are __InstanceCreationEvent , __InstanceModificationEvent , and __InstanceDeletionEvent .
Hence, monitoring resources on a system involves monitoring of these system classes. The later
chapters in this book dig deep in to the intrinsic events and show examples of subscribing to
these events.
Extrinsic
Events
Extrinsic events
represent
events
that
do
not
directly
link
to
standard
WMI
model.
For
example,
Windows registry defines extrinsic events for all registry change events. For intrinsic events,
having a WMI provider isn’t mandatory. This is mostly because they are defined within the
standard WMI model and WMI takes care of these if there is no WMI provider for a given
resource in the standard WMI model. However, since extrinsic events are outside of the
standard WMI model, having a WMI provider is mandatory. The later sections of this book will
provide an in‐depth discussion on the Windows registry events and show a few examples.
Timer
Events
Timer events are a specialized kind of intrinsic event. WMI uses preconfigured event timers
within the
repository
to
generate
timer
events.
In
the
pre
Windows
2003
days,
we
had
to
use
__AbsoluteTimerInstruction7 and __IntervalTimerInstruction8 to create absolute and interval
timer instructions, respectively. However, with the Win32_LocalTime class, this isn’t necessary
any more. We shall see how to use this class to create timer events and examples of how to use
the timer events to create complex scheduling tasks in the later parts of this book.
7 __AbsoluteTimerInstruction class: http://msdn.microsoft.com/en-us/library/aa394620(v=vs.85).aspx 8 __IntervalTimerInstruction class: http://msdn.microsoft.com/en-us/library/aa394654(v=VS.85).aspx
-
8/18/2019 WMI Query Language via PowerShell
34/56
[33]
Before we dig in to the event types, it is important to understand the WMI query syntax used
for the above query types. The WMI query syntax for event queries is a bit different and
deserves a discussion.
WQL
Syntax
for
event
queries
As we discussed earlier, we use SELECT statement for event queries too. We can combine this
with other keywords such as WITHIN, HAVING, and GROUP to change how we receive these
WMI events. Here is the general syntax for WQL event queries:
EVENT‐WQL = “SELECT” “FROM” /
OPTIONAL‐WITHIN = ["WITHIN" ]
INTERVAL = 1*DIGIT
EVENT ‐WHERE
= ["WHERE"
]
EVENT ‐EXPR = ( ( “ISA” ) /
)
["GROUP WITHIN"
( ["BY" [ DOT] ]
["HAVING" ]] )
INSTANCE ‐STATE = “TARGETINSTANCE” / “PREVIOUSINSTANCE”
In the
above
syntax
specification,
we
know
the
SELECT,
FROM,
and
WHERE
keywords.
There
are
other keywords such as WITHIN, GROUP, BY, and HAVING. Let us look at each one of these
keywords now.
WITHIN
WITHIN keyword is used to specify the polling interval or grouping interval (when used with
GROUP clause) for the events. A polling interval is the interval that WMI uses as the maximum
amount of time that can pass before notification of an event must be delivered. The general
syntax to specify the polling interval,
SELECT
*
FROM
eventclass
WITHIN
interval
WHERE
property
=
value
The polling interval value is specified as number of seconds and is a floating point number. So,
we can specify values smaller than one second. However, specifying a polling interval smaller
than one second (for example, 0.1) may cause system slow down due to the resource intensive
nature of event queries. The recommended values for the polling interval really depend on the
event class. Never use a small value here unless you really need the event notification to be
delivered immediately.
-
8/18/2019 WMI Query Language via PowerShell
35/56
[34]
Let us look at an example:
#Build a WMI query for receiving an event $query = "Select * from __instanceCreationEvent WITHIN 10 WHERETargetInstance ISA 'Win32_Process'"
#Register the event Register-WmiEvent -Query $query -Action {Write-Host "New Process created"}
GROUP
Using GROUP clause causes WMI to generate a single notification to represent a group of
events. When used in a WMI event query, this returns an instance of __AggregateEvent that
contains an embedded object of one of the instances received during the grouping interval and
the number of such events received. These two are represented by ‘Representative’ &
‘NumberOfEvents’ properties respectively.
The grouping
interval
specifies
the
time
period,
after
receiving
an
initial
event,
during
which
WMI should collect similar events. The GROUP clause must contain a WITHIN clause to specify
the grouping interval and can contain either the BY or the HAVING keyword, or both.�
top related