Working with Dates in WMI - Building Queries with Dates
(Page 5 of 5 )
Now that you’ve seen how to convert between VBScript Date values and WMI datetime values, let’s move on to the good stuff and learn how to construct queries using dates and times.
Keep in mind that datetime values must contain all parts for both the date and the time. Any unused values should be added as zeros.
Remember that datetime values are nothing more than strings. Thus, they can be very easily added to a query, since queries themselves are strings. Like other string values, datetime values should be surrounded with single quotation marks.
dtmTargetDate = #09/01/2008#
Set datetime = CreateObject("WbemScripting.SWbemDateTime")
datetime.SetVarDate(dtmTargetDate)
strComputer = "."
Set objWMIServices = GetObject("winmgmts:{impersonationLevel=impersonate}!" & strComputer & "rootcimv2")
Set colFolders = objWMIServices.ExecQuery("SELECT * FROM Win32_Directory WHERE CreationDate > '" & datetime & "'")
For Each objFolder in colFolders
WScript.Echo objFolder.Name
Next
The WMI query in this example will list all files created since the date provided. It uses the W32_Directory class to iterate through the files on the current system, checking each file’s creation date. The W32_Directory’s CreationDate property returns a file’s creation date in standard WMI datetime format. Thus, you must convert a date to this format before querying this value.
As you can see, using date and time values in VBScript can be confusing. When you add WMI into the mix, this only gets more complicated. But if you take things slow, and think carefully, you can avoid most common pitfalls.
Also, keep in mind that both VBScript’s VT_Date format and WMI’s DateTime format are both relative to the local system’s regional settings. Whenever scripting across platforms or querying remote systems, you should always deal strictly with GMT times (and avoid time zones) whenever possible. Until next time, keep coding!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |