WMI Query Language Via PowerShell - Eddie Jackson

2y ago
100 Views
7 Downloads
1.72 MB
57 Pages
Last View : 2d ago
Last Download : 2m ago
Upload by : Kelvin Chao
Transcription

WMI Query Languagevia PowerShellRavikanth ChagantiExplore basics of WMI Query Language, different types of WMI queries, and learn howPowerShell can be used to retrieve WMI management information using WQL.

Table of ContentsIntroduction . 5Introducing WMI Query Language . 5WMI Query Types . 6Data Queries . 6Event Queries . 6Schema Queries . 7WQL Keywords . 7WQL Operators . 8Tools for the job . 10WBEMTEST . 10WMI Administrative Tools . 12[WMISEARCHER] type accelerator . 14PowerShell WMI cmdlets . 15WMI Data Queries . 17SELECT, FROM, and WHERE . 17Using Operators . 18ASSOCIATORS OF . 21ClassDefsOnly . 23AssocClass . 24ResultClass . 24ResultRole . 24Role . 28RequiredQualifier and RequiredAssocQualifier . 28REFERENCES OF. 29WMI Event Queries: Introduction . 31Event Query Types . 33Intrinsic Events . 33Extrinsic Events . 33Timer Events . 33WQL Syntax for event queries . 34WITHIN . 34[1]

GROUP. 35HAVING . 36BY . 36Intrinsic Event Queries . 38InstanceCreationEvent . 39InstanceDeletionEvent . 39InstanceModificationEvent . 39Extrinsic Event Queries . 43Monitoring registry value change events . 43Monitoring registry key change events . 44Monitoring registry tree change events . 45Timer Events . 46WMI Schema Queries . 49Using this. 50Using Class . 50WMI Event Consumers . 51Temporary Event consumers . 51Permanent Event consumers . 51Creating an event filter . 53Creating a logical consumer . 53Binding Event Filter and Consumer. 54Introducing PowerEvents . 54Creating an event filter . 55Creating an event consumer . 55Binding Event filter and consumer. 55[2]

This book is dedicated to Andrew Tearle, the mostpassionate PowerSheller and a good friend.Rest in peace Andy.[3]

AcknowledgementsI would like to thank Shay Levy (MVP), Aleksandar Nikolic (MVP), Philip LaVoie, and RobertRobelo for providing their feedback. Their feedback really helped shape the ebook and includeextra content that was not planned initially. Also, thanks to everyone who read my blog postson WMI query language and provided feedback. Your encouragement and support helped mewrite quite a bit about WQL and now this ebook.[4]

IntroductionWindows Management Instrumentation (WMI) is Microsoft’s implementation of Web BasedEnterprise Management (WBEM), which is an industry initiative to develop a standardtechnology for accessing management information in an enterprise environment. WMI uses theCommon Information Model (CIM) industry standard to represent systems, applications,networks, devices, and other managed components. CIM is developed and maintained by theDistributed Management Task Force (DMTF). We can write WMI scripts to automate severaltasks on local or remote computer(s).Windows PowerShell has a few cmdlets to retrieve the management data exposed by WMI. Wecan list these cmdlets by using:#Use Get-Command and mention WMI* as the NounGet-Command -Noun WMI*There are five cmdlets that are used to work with WMI. However, within the scope of this book,we shall use Get-WMIObject and Register-WMIEvent only. Get-WMIObject, in its basic usage,gets the instance(s) of a WMI class. So, for example, if we need to list out all drives of type 3(disk drives) in a system,Get-WMIObject -Class Win32 LogicalDisk Where-Object { .DriveType -eq 3}In the above method, we retrieve all instances of Win32 LogicalDisk and then pass it to WhereObject to filter out what we need. This can take a while depending on how many instances arethere. You can use an alternative approach by specifying -Query parameter instead of -Class.#This example uses -Query parameter and specifies the query using WQLGet-WMIObject -Query "SELECT * FROM Win32 LogicalDisk WHERE DriveType 3"Introducing WMI Query LanguageThe above example uses WMI Query Language to get the same information as the earlierexample but a bit faster. We can verify this using Measure-Command cmdlet.Let us see this in action:[5]

In the above example, we used three variations of Get-WMIObject to do the same job ofretrieving all instances of Win32 LogicalDisk where the DriveType is 3 (a disk drive). From theoutput, we can see that using -Query and -Filter are the fastest ways to retrieve the WMIinformation.Note-Filter, as we shall see in next chapters, is a variation of -Query. In fact, the value ofFilter represents the value of a WHERE clause when using -Query parameter. Whenusing -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 speedof execution is just one benefit. There are quite a few advanced querying techniques that canbe used to retrieve WMI information in an efficient manner. And, sometimes, such as workingwith WMI events, WQL becomes a necessity. We shall see each of these benefits as we proceedfurther.So, what is WQL?The WMI Query Language is a subset of the American National Standards Institute StructuredQuery Language (ANSI SQL)—with minor semantic changes. Similar to SQL, WQL has a set ofkeywords & operators and supports three types of queries.WMI Query TypesWMI supports three types of queries:1. Data Queries2. Event Queries3. Schema QueriesData QueriesThis type is the simplest form of querying for WMI data and the most commonly used querytype when working with WMI. Data queries are used to retrieve class instances and dataassociations. The earlier example, where we queried for all instances of Win32 LogicalDiskwhere 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 QueriesThe event queries are used to create WMI event subscriptions. For example, using thesequeries we can create an event subscription to notify whenever a USB drive gets attached tothe system. The WQL keywords such as GROUP, HAVING, and WITHIN are used when creatingevent queries. The event queries are critical when we want use PowerShell cmdlets such asRegister-WMIEvent for creating temporary event consumers. Using this cmdlet, we can createWMI event consumers and invoke an action when the event gets triggered. We shall see moreon this in the subsequent sections.[6]

Schema QueriesSchema queries are used to retrieve class definitions (rather than class instances) and schemaassociations. In layman’s terms, these queries are used to get information about WMI and itsstructure. Schema queries return a result set of class definition objects rather than actualinstances of classes. The WQL keywords such as SELECT, ASSOCIATORS OF, REFERENCES OF, andISA are used in schema queries and of course, in a slightly different way than how data queriesuse these keywords.WMI does not support cross-namespace queries or associations. Using WQL, we cannot queryfor 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. We cannotmodify the WMI objects using WQL.WQL KeywordsSimilar to SQL, WQL queries use keywords to retrieve data from the management objects. WQLhas 19 keywords to perform these queries against WMI repositories. Even though there are 19WQL keywords, only a few of them can be used in all three possible query types we discussedearlier. The following table lists all the WQL keywords and lists the query type in which they canbe used.KeywordANDQuery TypeData Schema EventXXASSOCIATORS onCombines two Boolean expressions, and returnsTRUE when both expressions are TRUE.Retrieves all instances that are associated with asource instance. Use this statement with schemaqueries and data queries.References the class of the object in a query.Specifies the class that contains the propertieslisted in a SELECT statement. WindowsManagement Instrumentation (WMI) supportsdata queries from only one class at a time.Causes WMI to generate one notification torepresent a group of events.Filters the events that are received during thegrouping interval that is specified in the WITHINclause.Comparison operator used with NOT and NULL.The syntax for this statement is the following:IS [NOT] NULL (where NOT is optional)Operator that applies a query to the subclasses ofa specified class[7]

KEYSONLYXLIKEXNOTXNULLXORXREFERENCES OFXXSELECTTRUEWHEREXXXXWITHINFALSEXXXXXXXXUsed in REFERENCES OF and ASSOCIATORS OFqueries to ensure that the resulting instances areonly populated with the keys of the instances. Thisreduces the overhead of the call.Operator that determines whether or not a givencharacter string matches a specified pattern.Comparison operator that use in a WQL SELECTqueryIndicates an object does not have an explicitlyassigned value. NULL is not equivalent to zero (0)or blank.Combines two conditions. When more than onelogical operator is used in a statement, the ORoperators are evaluated after the AND operators.Retrieves all association instances that refer to aspecific source instance. The REFERENCES OFstatement is similar to the ASSOCIATORS OFstatement. However, it does not retrieve endpointinstances; it retrieves the association instances.Specifies the properties that are used in a query.Boolean operator that evaluates to -1 (minus one).Narrows the scope of a data, event, or schemaquery.Specifies polling or grouping interval.Boolean operator that evaluates to 0 (zero).We shall look at each of these keywords when we start discussing different types of WMIqueries in-depth.WQL OperatorsSimilar to arithmetic operators, WQL uses the same set. The following table lists all theoperators supported in WQL.Operator ! or DescriptionEqual toLess thanGreater thanLess than or equaltoGreater than orequal toNot equal to[8]

A few WQL keywords such as IS, ISA, NOT, and LIKE1 can also be considered as operators. Inthese keywords, IS and IS NOT operators are valid in the WHERE clause only if the constant isNULL.Once again, there is a detailed discussion on how to use these operators in the upcomingsections.1LIKE operator is not available in Windows 2000[9]

Tools for the jobIn the first chapter, we looked at what is WQL, different types of WMI queries, and WQLkeywords & operators. Before we dig deep into this subject, we shall look at different toolsavailable to execute WMI queries.There are several tools that can be used to execute WMI queries. This includes WBEMTest.exe WMI tools [WMISEARCHER] type accelerator in PowerShell PowerShell WMI cmdletsIn the subsequent sections, we shall look at each of the above mentioned tools in detail and seehow WMI queries can be executed using these tools. However, rest of the chapters in this bookwill focus only on WMI PowerShell cmdlets and refer to other tools only when required.WBEMTESTWBEMTest.exe is present on every computer that has WMI installed. This tool provides a greatway to explore WMI classes and instances. This was initially developed to test WMI COM APIand hence can do everything you can achieve using WMI.To open WBEMTest.exe,Click Start- Run, type “WBEMTest.exe” and Press Enter. This should open a GUI window similarto what is shown below:[10]

Now, we can connect to a WMI namespace using the “Connect” button at the top.Assuming you have the necessary permissions to access root\cimv2 namespace, just click“Connect”. Once we are connected to the root\cimv2 namespace, we can perform severalactions such as enumerating classes, creating instances, executing methods, and also executingWMI queries. The last part is what we are interested in.[11]

In the above window, we can use the “Query” and “Notification Query” options to executeWMI queries. The “Query” option can be used for WMI data and schema queries. And,“Notification Query” can be used for running WMI event queries.As an example, we shall now look at how we can execute simple data queries and save thenotification queries part for a later part of this book.Click on the “Query” button in the WBEMTest window; enter a WQL statement as shown aboveand click “Apply”.The query result window shows all instances of Win32 Process class. This is it. WBEMTest is anexpert tool and is a great tool to explore WMI interfaces.WMI Administrative ToolsWMI administrative tools can be used to view and edit WMI classes, properties, qualifiers andinstances in a WMI repository. You can also use these tools to invoke WMI methods, manageWMI objects, register and receive WMI events. The free WMI tools download package includes1. WMI CIM Studio2. WMI Object browser3. WMI Event registration[12]

4. WMI Event viewerThese tools can be downloaded aspx?FamilyID 6430f853-1120-48db-8cc5f2abdc3ed314NoteWMI CIM Studio can be used to execute data/schema queries. WMI Tools do notsupport executing WMI event queries.Once the WMI tools are installed, open WMI CIM studio by selecting Start - All Programs - WMI Tools - WMI CIM Studio. This prompts for the WMI namespace selection and credentials.In the resulting browser window, click onanother window as shown here:icon at the top-right corner. This brings up[13]

Type ‘Select * from Win32 Process’ (without quotes) in the query textbox and click “Execute”.This shows all the instances of Win32 Process class. Similarly, we can execute schema queriesusing CIM Studio. The WMI tools are used for many other purposes than just executing WMIqueries. These tools are also a great way to explore and learn about WMI.[WMISEARCHER] type acceleratorWindows PowerShell provides shortcuts to allow direct access to .NET namespaces. Theseshortcuts are called type accelerators. There are three type accelerators to access WMImanagement namespaces.WMI type Retrieve single instance of a WMI class.Access static properties and methods of aWMI class.Search for WMI objectsWithin the scope of this book, we are more interested in how [WMISEARCHER] type acceleratorcan be used to run WMI queries.[WMISEARCHER] is a shortcut for System.Management.ManagementObjectSearcher2 .NETnamespace. The way we use this type accelerator is:1. Provide a WQL statement.2. Invoke the Get() method to execute the WMI query.2ManagementObjectSearcher Class - spx[14]

Simple! And, this is how we use it at the PowerShell console.NoteTo see a list of all members of [WMISEARCHER] accelerators you can pipe[WMISEARCHER]"" to Get-Member cmdlet. 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 servicesin “running” state. By default, the scope of the query is set to root\cimv2 namespace. In caseyou 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 theinstances of MSPower DeviceEnable class. Using this type accelerator, we can set someextended properties3 such as blocksize, timeout, etc. These options are not available in thebuilt-in WMI cmdlets method.We can use [WMISEARCHER] for some quick access to WMI information but it gets quiteverbose soon. This brings us to the last section of this chapter – using PowerShell WMI cmdletsto execute WMI queries.PowerShell WMI cmdletsAs mentioned in the first chapter, PowerShell v2.0 includes five WMI cmdlets. Within these fivecmdlets, Get-WMIObject and Register-WMIEvent can be used to execute WMI queries. GetWMIObject can be used for data/schema queries while Register-WMIEvent can be used fortriggering event queries.We have seen several examples using Get-WMIObject already. So, here is a quick example of anevent 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 getscreated on the system. Don’t worry much even if you don’t understand anything here. WMIevent queries require a complete discussion and we shall see that in the later chapters.3[WMISEARCHER] Query options: gement.enumerationoptions.aspx[15]

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!4Sapien’s WMI browser - http://www.sapien.com/[16]

WMI Data QueriesWMI data queries are the simplest form of querying for WMI data. WMI data queries are usedto retrieve class instances and associations. There are several keywords and operators that areused 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 inchapter one.In this chapter, we shall start looking at the most commonly used form of data queries and thenmove on to data queries for association. As a part of the examples, we shall look at how someof the operators are used, gotchas when using operators, and finally how to use multipleoperators in a query.SELECT, FROM, and WHEREThe general syntax when using SELECT keyword for data queries is:SELECT [* Property Names] FROM ClassNameSo, if you want to get all instances of Win32 Service class and all properties, query "SELECT * FROM Win32 Service"Get-WMIObject -Query queryThis will list all instances of Win32 Service and properties of each instance.NoteRemember that you can perform data queries only from one class at a time. Forexample, 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 canuse WHERE clause to filter that. Here is how we do it: query "SELECT * FROM Win32 Service WHERE Name 'AudioSrv'"Get-WMIObject -Query queryThis will list only one instance and the properties of that instance. WHERE is used to narrow thescope 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 constantSELECT * FROM class WHERE constant operator property[17]

In the above two forms, property denotes a valid property of a WMI instance, operator is anyvalid WQL operator and constant must be of the correct type for the property. Let us look at anexample for the second form of using WHERE. query "SELECT Name, State FROM Win32 Service WHERE 'AudioSrv' LIKE Name"Get-WMIObject -Query queryIn the above example, we replaced ‘*’ with Name & State to limit the number of properties inthe 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 and in case ofremote query execution, we are reducing the bandwidth required to execute the query and theamount of data we get in return.NoteThe above query outputs the system properties such as PATH, etc in the output. Thisis because the default formatting for the WMI class is lost when we specify a selectedset of properties.Using OperatorsIn this section, we shall look at different operators that can be used with WMI data queries andhow we can use them.LIKEIn the preceding example, we filtered out the instances by using WHERE clause and specifyingthat we need only one instance of Win32 Service. What if we don’t know the exact servicename but we know that it has the word ‘audio’ in it. query "SELECT * FROM Win32 Service WHERE Name LIKE '%Audio%'"Get-WMIObject -Query queryThis will list all the services that have the word ‘audio’ in the name of the service.NoteYou can use -Filter parameter instead of a WHERE clause or even -Query. When using Filter, Get-WMIObject cmdlet builds the required WQL statement internally. Forexample: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 wildcard character for specifyingsomething like “get anything that has the word”. However, in WQL, ‘%’ is the wild cardcharacter when using LIKE keyword. There are also other meta characters such as [ ], , andthat we can use with LIKE operator.Here are some examples of how we use these additional meta characters.[18]

query "SELECT * FROM Win32 Service WHERE Name LIKE '[af]%'"Get-WMIObject -Query queryThe above query gets us all services with a name that starts with ‘a’ or ‘f’. The way we use ‘[ ]’ isvery 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 ‘[ ]’ metacharacter but specify the range. Here is how we do it: query "SELECT * FROM Win32 Service WHERE Name LIKE '[a f]%'"Get-WMIObject -Query queryNoteYou can either use ‘[a f]%’ or ‘[a-f]%’ in the above query. Although, MSDNdocumentation 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 queryThe 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 namesnot starting with the characters in the range.The last meta character is ‘ ’ and it matches exactly one character in the specified positionsimilar to ‘?’ in DOS. Here is how we use it. query "SELECT * FROM Win32 Service WHERE Name LIKE '%a diosrv%'"Get-WMIObject -Query queryWhat we are trying in the above query is obvious. The ‘ ’ gets replaced by any character andthe matching service will be listed in the output.AND, OR, and NOTWe 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' ANDStartMode 'Manual'"Get-WMIObject -Query querySimple! By using AND, we specify that we need both conditions to evaluate to TRUE. What if wewant to list all services that are in ‘running’ state and StartMode set to ‘manual’ and the servicename starts with the characters ‘a’ or ‘f’. We have seen the first part of this query already. From[19]

the description of the problem, we know that we need to use another AND operator. Here ishow the query will look like: query "SELECT * FROM Win32 ServiceWHERE (State 'Running' AND Star

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

Related Documents:

WMI WFR 1612 28 1 6 17 NW CO Boulder WMI 1WFR 3 1712 NW CO Fort Collins WMI WFA 1 4 17 1 5 17 NW WY Yellowstone-Lamar WMI WFR 15 1714 NW OR Portland WMI WFR 16 1715 NW WA Walla Walla WMA WFR 17 1713 NW CO Lakewood WMI WFR 19 1718 NW CO Colorado Springs WMI WFR 19 1718 NW WY Laramie .

File extensions PS1 -Windows PowerShell shell script PSD1 -Windows PowerShell data file (for Version 2) PSM1 -Windows PowerShell module file (for Version 2) PS1XML -Windows PowerShell format and type definitions CLIXML -Windows PowerShell serialized data PSC1 -Windows PowerShell console file PSSC -Windows PowerShell Session Configuration file

To run Azure PowerShell in PowerShell 5.1 on Windows: 1. Update to Windows PowerShell 5.1 if needed. If you're on Windows 10, you already have PowerShell 5.1 installed. 2. Install .NET Framework 4.7.2 or later. There are no additional requirements for Azure PowerShell when using PowerShell Core. Tip: Always make sure to keep PowerShell up to date.

Adding Remote WMI Access In order for the wmiagent user to return data remotely from WMI, access to the WMI namespace CIMV2 must be granted. Click Start, choose Run.Type WMImgmt.msc and click OK. Right click on WMI Control (local) and select Properties. Click the Security tab of the WMI Control Properties window. Expand Root and select CIMV2. Click the Security button.

WMI WFR 12 27 18 12 5 18 Bainbridge Island NW WA WMI WFR 1 4 19 1 13 19 Juneau NW AK WMI WFR 1 4 19 1 13 19 Walla Walla NW WA WMI WFR 1 4 19 1 13 19 Walla Walla NW WA WMI wfa 1 5 19 1 6 19 Gardiner NW MT WMI wfa 1 5 19 1 6 19 Portland NW OR SOLO wfa 17 193 Corvallis NW OR .

What is Windows Powershell? Windows Powershell is an object-oriented programming language and functional programming language developed for system administrators and power users. Powershell is an explorer's scripting language, with built in help, command discovery and can access .NET Framework. Powershell is based on Microsoft .NET that

NOLS-WMI WFR 1 26 2 4 Woodinville NW WA 750-785 NOLS-WMI WFA 1 27 1 28 Bozeman NW MT 260 SOLO WFA 1 27 1 28 Corvallis NW OR NOLS-WMI WFA 1 27 1 28 Eugene NW OR 235- 265 NOLS-WMI WFA 1 27 1 28 Silverdale NW WA 235-265 NOLS-WMI WFR 2 2 2 11 Lyons NW CO 730 .

Carson-Dellosa CD-104594 2 3 1 Day 1: Day 2: 55 6 10 8 4 5 Day 3:; ; 8; 7