2

I've seen atleast two other questions regarding WMI but none had an answer to my question, so here it is;

I was experimenting with the WMI interface in my code. Basically this is what i have right now and it works. But it seems to me i could write it more efficiently:

public bool GetUsbStateById(string id) { bool returnValue = false;

  try
  {
    ObjectQuery query = new ObjectQuery();
    query.QueryString = string.Format("Select * From Win32_PnPDevice");
    ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(query);

    List<ManagementObject> results = (from ManagementObject mo in mySearcher.Get().AsParallel()
                                      where mo["SystemElement"].ToString().ToUpper().Contains(id.ToUpper())
                                      select mo).ToList();

    if (results.Count > 0)
      returnValue = true;
  }
  catch (Exception ex)
  {
    // TODO: implement logging
  }

  return returnValue;
}

So what happens here is that i get a list of ManagementObjects from the ManagementObjectSearcher. This works fine and also returns the exact results as i expect it to work.

But it seems redundant to me. Because, first i get the whole list, and then filter it. But because it uses WQL to fill the list, i assumed that i could implement something like this:

query.QueryString = string.Format("Select * From Win32_PnPDevice where SystemElement Like '%{0}%'",id);

this keeps throwing an exception that the query is not correct.

so i tried this instead:

query.QueryString = string.Format("Select SystemElement From Win32_PnPDevice);

This works as well, so next i tried Win32_PnPDevice.SystemElement, but this didn't work either.

any examples i looked at on the internet showed something like this

Select * From Win32_Service Where Name Like "%SQL%"

but c# can't parse the double quotes that surround the %SQL% statement there, using an the \ escape character yielded no results either.

To test my code and the code posted below i used the WMI Code Creator from Microsoft

wterbeek
  • 451
  • 9
  • 26
  • 1
    so apparently microsoft didn't implement the like operator for ref classes as discussed here http://social.technet.microsoft.com/Forums/nl-BE/winserverpowershell/thread/24981775-e105-42a8-8313-b0b86972f6c3 – wterbeek Feb 18 '13 at 15:15

1 Answers1

3

if you want to run like query in WMI then you can use below example:

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
              string strSearchText="win";
              string strSearchQuery=string.Format("SELECT * FROM Win32_Service where Name like '%{0}%'",strSearchText);
              ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",strSearchQuery  );

            foreach (ManagementObject queryObj in searcher.Get())
            {
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Win32_Service instance");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Name: {0}", queryObj["Name"]);
            }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

But you can not apply like query on Win32_PNPDevice as discussed

Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
  • i tried using that with my code, but as i stated before that doesn't seem to work, even though i except it to work. the code i used is the following (taken from the WMI code creator from microsoft) – wterbeek Feb 18 '13 at 14:31
  • why have you removed your search query – Mohammad Arshad Alam Feb 18 '13 at 14:34
  • yes i tried your code, and it did work. i removed the query because i could get in the right format. give me a minute and i'll add it again – wterbeek Feb 18 '13 at 14:35
  • i tried using that with my code, but as i stated before that doesn't seem to work, even though i except it to work. the code i used is the following (taken from the WMI code creator from microsoft) try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPDevice where SystemElement like '%HDAUDIO%'"); } catch (ManagementException e) { } my apollogies for the format – wterbeek Feb 18 '13 at 14:37
  • the error i get is that the query is not in the correct syntax. i assume this has something to do with the like statement. because when i replace the asterisk with SystemElement it parses correctly and returns values – wterbeek Feb 18 '13 at 14:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24711/discussion-between-arshad-and-wterbeek) – Mohammad Arshad Alam Feb 18 '13 at 14:44