Script Tips

Just What You Needed

Make your scripts run more efficiently -- fine-tune your queries by making them call just what you need and not the other, unnecessary stuff.

I'm preparing for a class I'm teaching this Fall (see www.scriptingtraining.com for the details) and I was playing around with WMI, trying to come up with some good techniques for fine-tuning queries.

The best one I can think of, which I wanted to share with you in this week's column, is to write your WMI queries to be as specific as possible. Here’s an example of a WMI query that isn’t very specific:

Dim objWMI, strComputer
Dim colResults, objResult, strWMIQuery
strComputer = "REMOTEXP"
Set objWMI = GetObject("winmgmts:\\" & _
   strComputer & "\root\cimv2")
strWMIQuery = "SELECT * FROM Win32_OperatingSystem"
Set colResults = objWMI.ExecQuery(strWMIQuery)
For Each objResult In colResults
   objResult.Reboot
Next

Now, this isn't going to cause any major performance slowdown, but notice that the query is retrieving all instances of Win32_OperatingSystem, and it's retrieving all of the instances' properties -- but not doing anything with them. The script is just executing each instance's Reboot method.

Whenever possible, you want to just retrieve the instances you need, and only the properties you need. In this case, we don't need any properties, so we should just select a single small one to fine-tune things as much as possible. Here's the revised query:

Dim objWMI, strComputer
Dim colResults, objResult, strWMIQuery
strComputer = "REMOTEXP"
Set objWMI = GetObject("winmgmts:\\" & _
   strComputer & "\root\cimv2")
strWMIQuery = "SELECT Primary FROM " & _
   "Win32_OperatingSystem WHERE Primary = True"
Set colResults = objWMI.ExecQuery(strWMIQuery)
For Each objResult In colResults
   objResult.Reboot
Next

Now, I'm only getting one instance (the only one that usually exists), and I'm only getting one property. So this is a much more efficient, resource-friendly version of the query. Try to fine-tune your WMI queries in this fashion. It's a good practice and in some cases can save time and effort.

About the Author

Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.

comments powered by Disqus
Most   Popular

Upcoming Training Events