Event Scripting with WMI

So you’re really starting to figure out this whole scripting thing. That’s great, but now you’re beginning to realize that you want your scripts to work more like full applications, right? Let’s learn a way to bridge the gap between scripting and full-blown application development.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
May 14, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

We all know that you can create a script to perform a given list of procedures.  That’s cool.  We even know that we can schedule or loop them to make them recurring.  That’s nifty too.  But what you really want is to be able to write a script that reacts to something else!

How about a script that restarts your web server if it crashes?  Or how about a script that maintains an order database every time you receive an email order?  Now those would be useful scripts.

There’s just one problem.  How can WSH know when those particular things occur?  The answer is simple.  It’s called Event Programming—and lucky for us, both VBScript and WMI are event-driven technologies!

In programming there are three basic types of elements: methods (including functions and subroutines), properties, and events.  You’re already familiar with the first two.  We use those every day.

An event typically has two parts: an event method and an event sink.  We make a call to the event method to start the process off.  The method wants to know if a particular event occurs so it drops an event sink in memory.

Think of the event sink like a Boolean flag.  It has an initial value of False (i.e. the event hasn’t happened yet).  The sink then waits in memory until the event occurs.  At this point you can consider it to be True.

The event method checks back with the event sink periodically until either the event has occurred or until the request times out.  It then returns a value indicating its exit code.

Okay, so it’s actually more detailed than that, but you get the idea.

Since VBScript is an event-driven language, events are actually very important to VBScript’s functionality.  Unfortunately for us, very few events are directly available to us within the WSH environment.  That’s different with WMI, however.

Introduction to WMI

WMI provides a few basic events that, when used properly, can be very useful.  Take for example the __InstanceCreationEvent.  This event allows us to know when something gets created.

Okay, so what is something?  Well, simply put—whatever we want to watch.  Maybe we want to know when a file is created.  Or perhaps we’d like to know when a new key is added to the registry.  How about knowing when a program starts?

All right, I’m getting a little carried away.  Let’s take this slowly and look at an example.  We’re going to wait for a file to be created and then delete it.  Why?  Because it’s a pointless example, that’s why.

I’m going to assume you’ve worked with WMI to some extent before.  If you haven’t, you’ve probably at least seen it.  If not, well, just try to keep up.  It looks intimidating but it’s really not that bad.

WMI consists of a series of classes that contain information about the environment.  Some of them are intrinsic classes, native to WMI, and some are made available by other Providers. All you really need to understand at this point is that WMI functions somewhat like a database.  All interactions take the form of queries.

If you know any form of SQL you will find this very easy.  The specific variation used by WMI is known as WQL.

We begin our script by connecting to the WMI service with the cimv2 provider.  This part should be a snap for you at this point.

strComputer = "."

Set objWMIService = GetObject("winmgmts:" & strComputer _

   & "rootcimv2")

Using __InstanceCreationEvent

Next, you need to issue a query using the WMI Service object’s ExecNotificationQuery function.

Set colEvents = objWMIService.ExecNotificationQuery _

   ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _

      & "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _

      & "TargetInstance.GroupComponent= " _

      & "'Win32_Directory.Name=""c:\test""'")

This query probably looks a lot different from the WMI queries to which you are accustomed.  It’s a little complex, but I’ll try to simplify it for you.  Here’s how it translates into English.

We’re looking for all (SELECT * FROM) creation events (__InstanceCreationEvent), WITHIN 10 seconds, WHERE the returned event (TargetInstance) is a (ISA) file contained in the C:test directory. (The remainder of the query).

It’s important to note that the WMI query will keep running.  You must stop it by ending the script, otherwise it will continue indefinitely until the WMI Service is stopped.

Don’t forget that paths must be contained in quotation marks and all backslashes must be escaped with backslashes.

If you don’t fully understand this query, that’s okay. You can use it as a model for other queries just by changing the folder location.

So, WMI processes our request and returns a collection of events fitting our description that occurred within the timeout period.

Now we need to return the results.  We’ll use the NextEvent function provided by the colEvents collection.  Of course, there’s no way of knowing how many times our event occurred so we’ll enclose everything inside of an endless Do…Loop.

Do While True

   Set objEvent = colEvents.NextEvent()

   WScript.Echo "A new file was just created:", _

      objEvent.TargetInstance.PartComponent

   Exit Do

Loop

This Do Loop will continue forever.  I’ve used the Exit Do statement to demonstrate how you can stop this process after one iteration.  You could easily use a conditional statement to exit this as well.

If you only want to return a specific number of occurrences, try using a For…Next loop instead of the Do…Loop.

Even now, after ending the Do loop, our WMI query is still running.  You can end it by quitting the script or by setting the objWMIService equal to Nothing if you want the script to continue running.

Using __InstanceDeletionEvent

As you can probably imagine, the __InstanceDeletionEvent works the same way.  Just replace the event in your WMI query and let it go to work.  The script would look like this:

strComputer = "."

Set objWMIService = GetObject("winmgmts:" & strComputer _

   & "rootcimv2")

 

Set colEvents = objWMIService.ExecNotificationQuery _

   ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _

      & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _

      & "TargetInstance.GroupComponent= " _

      & "'Win32_Directory.Name=""c:\test""'")

 

Do While True

   Set objEvent = colEvents.NextEvent()

   WScript.Echo "File Deleted:", _

       objEvent.TargetInstance.PartComponent

Loop

This example will watch the C:test folder for file deletions.  All of the same rules apply: the query will run continuously until stopped and you must force it to exit the Do loop.

There is a plethora of different ways you can make use of the Create and Delete events.  It doesn’t just apply to files.  You can use this to monitor folders, drive letters, registry keys, services, and more.  Play around with it and see what you can come up with.

Stick around for the second part of this series, when we’ll explore two other event types that WMI makes available to us.  Until next time, keep coding.

blog comments powered by Disqus
WINDOWS SCRIPTING ARTICLES

- More Windows Scripting Workarounds from Nilpo
- Overloading Methods and More in VBScript
- Improving MFC for Windows Vista
- Regular Expressions in VBScript
- Working with Dates in WMI
- Completing Calendars with VBScript Date Func...
- Building Calendars with VBScript Date Functi...
- Working With Dates and Times in VBScript
- Designing WCF DataContract Classes Using the...
- Understanding Dates and Times in VBScript
- Working With Arrays in VBScript
- Compressed Folders in WSH
- Using .NET Interops in VBScript
- Nilpo`s Scripting Secrets, Vol I
- Database operations using Silverlight 2.0 WC...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials