Help formulating a more specific WMI query, not using a collection

Posted on 2008-02-11
Medium Priority
Last Modified: 2010-04-21
When programming in WMI one typicall performs a WMI Query like "Select * from Win32_BIOS". The return is typically loaded into a collection and then we loop through the collection in a statement something along the lines of "For each objItem in wmiCollection".  The properties would then become (in the case of the BIOS serial number) objItem.SerialNumber.

I'd like to query specific information and assign it directly to a variable with out needlessly looping through a collection of properties I am going to discard anyway. Is there a way to skip the whole collection assignment / For/ Next loop ?

The code I am using looks like this (straight from the WMI Code Generation tool from M$)

                Dim connection As New ConnectionOptions
                connection.Username = userNameBox.Text
                connection.Password = passwordBox.Text
                connection.Authority = "ntlmdomain:DOMAIN"

                Dim scope As New ManagementScope( _
                    "\\FullComputerName\root\CIMV2", connection)

                Dim query As New ObjectQuery( _
                    "SELECT * FROM Win32_BIOS")

                Dim searcher As New ManagementObjectSearcher(scope, query)

                For Each queryObj As ManagementObject In searcher.Get()

                    Console.WriteLine("Win32_BIOS instance")
                    Console.WriteLine("SerialNumber: {0}", queryObj("SerialNumber"))

            Catch err As ManagementException
                MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
            Catch unauthorizedErr As System.UnauthorizedAccessException

                MessageBox.Show("Connection error (user name or password might be incorrect): " & unauthorizedErr.Message)
            End Try

 What I'd like to do is ditch the whole For Next loop and assign my end result directly to a variable;  Where the Query would be "SELECT SerialNumber from Win32BIOS"..... I'm creating a XML Driven routine and am only after exacting properties.

I'm VERY new to VB.NET. And even newer to trying to work with WMI through VB.NET.
Question by:jjthomas3
  • 3
  • 3
LVL 96

Expert Comment

by:Bob Learned
ID: 20868676
1) The ManagementObjectCollection does not have an indexer, so you can't reference by index.

2) The Get method only returns 1 item, so there isn't much hit to use a For statement.

3) I don't think that there is a way with WMI to get a single object.  Even the ManagementClass.GetInstances returns a ManagementObjectCollection.


Author Comment

ID: 20869533
That's a bummer.

I know that when I perform "Select SerialNumber from Win32_BIOS" it only returns the serial number and no other members. It just feels like such a wast to me to loop through a collection to get one point of data.  I guess my thinking is more efficent than the language.

While it may not be very taxing to perform this simple loop is presents me with code that is needed only to compensate for Microsof't lack of vision on the small details.....If I can formulate a query that returns only one data-point I should be able to assign it straight to a variable.....

Lets see if anyone else has any suggestions for me..... although I have to say it is looking discouraging.

LVL 96

Expert Comment

by:Bob Learned
ID: 20869590
I agree that it is inefficient to loop to get a single value, but you need to look at the bigger picture to determine if it is even important to worry about inefficiency.  Most of WMI has more than 1 record, so I think that the developers didn't think about getting a single record.  Efficiency is really only important if you are looping 1000's of times--you won't notice any difference with a single record loop versus getting a single value.

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

LVL 41

Accepted Solution

graye earned 2000 total points
ID: 20874624
Some WMI classes have a "Primary Key"... and will therefore allow you to ask for a specific instance without doing any looping.  For example, the DeviceID field in the Win32_LogicalDisk class is a primary key,  so you can get an instance of that one object with the following:

Dim obj as new System.Management.ManagementObject("\\" & RemotePC & "\root\cimv2:Win32_LogicalDisk.DeviceID='C:'");

Take a look at the following article (and downloadable source code).... there is specific mention of this "primary key" technique

LVL 96

Expert Comment

by:Bob Learned
ID: 20874895
WMI is such a big topic that I can always be learning new things.  *BIG GRIN*


Author Comment

ID: 20880185

 Thank you for the great link and the information. I'm trying to bring one of my freeware applications forward into the future because...well...I use it every day. The old version had hard-coded WMI Queries that looped through each various Win32_ classes, pulling out several pieces from each. I am trying to grapple with learning XML and get the new version to use a XML file so people can provide their own WMI queries.

LearnedOne, oh boy is it ever a big topic.....my head hurts :)

Author Closing Comment

ID: 31429811
Thank you, I managed to use the information and samples @ the site you provided to restructure my program a bit. I got much closer. There are just soooooooo many points of info out there on WMI.

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
In this video I will demonstrate how to set up Nine, which I now consider the best alternative email app to Touchdown.
Watch the video to learn how one can deal with PST file corruption issue with an outstanding Kernel for Outlook PST Repair Tool easily. Using this tool, non-technical users can swiftly perform the repair process to restore their essential data witho…

588 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question