The Art of Coding without Coding (WMI Part 1)

One of the great things about using the Systems.Management namespace is all of the information you can retrieve.  Adding a reference to the Systems.Management namespace into your program will allow your application to query Windows Management Instrumentation(WMI).  Even the most seasoned veteran can’t remember all of the specific classes and namespaces, and beginners need help with query syntax.

Thanks for Chris Scoville at Microsoft, there is a tool that will generate complete WMI query code for your application, the WMI Code Creator.   Additionally, the application has a built in namespace browser that displays all the properties and methods of a class. 

Using the WMI Code Creator

The greatest thing about the WMI Code Creator for new programmers is that it generates a complete code block that can be pasted directly into your code editor, but you may get more than you want.  Using the Code Language menu item, choose the appropriate language.  For Visual Basic .NET, the application will generate code for a namespace and public class.  If you are wanting just the basic code to attach to a function or event within your application, you probably wont need the entire code block.  For example, suppose you want to use WMI to retrieve a list of printers on the local computer, and populate a listbox with those printers.  I’ll walk through this procedure step by step.

  • Create a new Windows Forms application using the New, Project, menu.
  • Drag a Button and a ListBox to the form from the toolbox
  • Start the WMI Code Creator if it isn’t running and choose Visual Basic .NET from the Code Language Menu
  • The NameSpace combo box should default to "root\CIMV2".  If it doesn’t, choose it from the dropdown list.
  • Select WIN32_Printer from the Classes dropdown.
  • Select Name from the properties list, you should now have the following code displayed in the WMI Code Creator Window:
Imports System
Imports System.Management
Imports System.Windows.Forms

Namespace WMISample

    Public Class MyWMIQuery

        Public Overloads Shared Function Main() As Integer

            Try
                Dim searcher As New ManagementObjectSearcher( _
                    "root\CIMV2", _
                    "SELECT * FROM Win32_Printer") 

                For Each queryObj As ManagementObject in searcher.Get()

                    Console.WriteLine("-----------------------------------")
                    Console.WriteLine("Win32_Printer instance")
                    Console.WriteLine("-----------------------------------")
                    Console.WriteLine("Name: {0}", queryObj("Name"))
                Next
            Catch err As ManagementException
                MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
            End Try
        End Function
    End Class
End Namespace

While this code is indeed complete, it contains a definition of a namespace and public class that we will not be needing for our example. 

  • Select the Try/End Try block of code and copy it to the clipboard.
  • Return to Visual Basic 2008 Express and doubleclick on button1.  It should open the code editor inside the Button1_Click event.
  • Paste in the code you copied from the WMI Code Creator.  Your Button1_Click event should now look like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
                "root\CIMV2", _
                "SELECT * FROM Win32_Printer")

            For Each queryObj As ManagementObject In searcher.Get()

                Console.WriteLine("-----------------------------------")
                Console.WriteLine("Win32_Printer instance")
                Console.WriteLine("-----------------------------------")
                Console.WriteLine("Name: {0}", queryObj("Name"))
            Next
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
        End Try
    End Sub

Before we continue, we need to get rid of all the red squigglies.  Your project doesn’t have any references to things such as ManagementObjectSearcher.

  • Choose Project, Add Reference from the menu.  Scroll down to System.Management and select it.  Click OK.
  • Above the line in your code that says "Public Class Form 1" add the following Imports System.Management
  • The Error List window (if visible) should now be clear, and the red squigglies should be gone.
  • See the four Console.Writeline statements?  We will not be using those, but take note of the last one.   
  • Delete the four Console.Writeline statements from the code.
  • Inside the For…Next block where you removed the Console.Writeline statements, insert the following entry
ListBox1.Items.Add(queryObj("Name"))

Your entire application code should look like the following example:

Imports System.Management
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
                "root\CIMV2", _
                "SELECT * FROM Win32_Printer")

            For Each queryObj As ManagementObject In searcher.Get()

                ListBox1.Items.Add(queryObj("Name"))

            Next
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
        End Try
    End Sub
End Class
  • Hit F5 or click the run button to see it in action, mine looks like this

printerlist

That’s it.  You just created a simple application that displays a list of printers on the local machine.  Not very useful and the information is already viewable from the built in capabilities of the operating system, but this is just an example of how the WMI Code Creator can help you develop your applications more quickly while minimizing the amount of code you have to create.  This barely touches the surface of WMI but you can see how easily it is to quickly create a simple application with the minimal amount of coding.  The article in this series will extend this program and make it more useful.  Check back soon.

You can download the WMI Code Creator for free from Microsoft.  I won’t try to link it here since stuff gets moved around all the time.  Google it, should be the first or second hit.

 

About the Code Samples

One of the purposes of this blog is for me to post all the bits of code, batch files, registry modifications, and scripts I’ve created over the years in managing networks and computers. There is no sense having this stuff sit around in my head or gathering dust on my hard drive, so I’m putting it here for all to enjoy, bash, or just comment on if they find it useful.

Over the years, many utilities and tools have been developed, and there are many more choices than there used to be. The choices nowadays can be overwhelming, remember there is no silver bullet. There are numerous ways to accomplish the same tasks, and administrators all seem to have their preference as to which tools they use. If you are starting out, read the FAQs, search the web, and by all means view sample code. Chances are someone out there has already encountered the problem and developed a solution. You may never need to write a single line of code if you don’t want to, but what fun would that be? So keep your arsenal of tools fully equipped and up to date, you never know when you’ll need them.

I’d like to state in advance that if you see something here that looks like a repeat of other code elsewhere, let me know. Personally, I don’t like duplicate information and if there’s a better way, by all means I’ll retire mine. Also, I am not about creating mass quantities of content by filling this site up with information from other sites. So, now I’m off to find all the KixTart, Batch, VBScript, WMIC, etc… code I’m hoarding and start to groom it for posting. Until then, thanks in advance for visiting and I hope you check back soon.

About the Samples

Most of the code samples on this site have been developed by me, and I hope you find them useful. Some are quite simple, some are a little more in depth. There are some out of the box custom solutions for problems you may encounter, and some solutions to problems that you may never encounter. Some are simply methods to perform tasks that can be done manually. There’s some snippets that don’t make sense if you are managing a few computers, but if you’ve got hundreds I hope you will find them useful.

I’m using a Plug-in that formats code so it will stand out from the rest of the text. Below is an example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MsgBox("Hello World!")
End Sub

 

Disclaimer

Although I’ve tested and used the code here extensively, I can not reproduce every potential environment or condition. I’ve taken great care to ensure functionality and accuracy. Since some of the code samples on this site do more than retrieve information, you assume all risk when using them. Please test all scripts in non production environment or on non critical information systems.

Code by Jason Stenklyft are provided ‘as is’ without warranty of any kind, either express or implied, including, but not limited to, the implied warranties of fitness for a purpose, or the warranty of non-infringement.

Without limiting the foregoing, Jason Stenklyft makes no warranty that:

The code will meet your requirements

The code will be uninterrupted, timely, secure or error-free

The results that may be obtained from the use of the code will be effective, accurate or reliable

The quality of the code will meet your expectations

Any errors in the code will be corrected.

 

Code obtained from Jason Stenklyft:

Could include technical or other mistakes, inaccuracies or typographical errors May be out of date, and Jason Stenklyft makes no commitment to update such materials Jason Stenklyft assumes no responsibility for errors or omissions in the scripts or documentation. In no event shall Jason Stenklyft be liable to you or any third parties for any special, punitive, incidental, indirect or consequential damages of any kind, or any damages whatsoever, including, without limitation, those resulting from loss of use, data or profits, whether or not Jason Stenklyft has been advised of the possibility of such damages, and on any theory of liability, arising out of or in connection with the use of these samples.

The use of the code obtained from Jason Stenklyft is done at your own discretion and risk and with agreement that you will be solely responsible for any damage to your computer system or loss of data that results from such activities. No advice or information, whether oral or written, obtained by you from Jason Stenklyft shall create any warranty for the code.