How to construct WMI query
Asked Answered
M

2

12

I'd like to find results that Name starts with param1, and ends with param2 but my code doesn't work

string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%' AND Name LIKE '%{1}'", param1, param2);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();

What's wrong?

For comparision

string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%'", param1);

works well

Marna answered 7/6, 2011 at 11:23 Comment(2)
Can you provide a small sample of what you are expecting? And is it just returning an empty collection?Raillery
Not empty. Collection of processes whose name starts with the param1 and ends with param2. I get then their idMarna
R
17

Try this:

string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%{1}'", param1, param2);

Adding some test info:

string wmiQuery = string.Format ( "SELECT Name, ProcessID FROM Win32_Process WHERE Name LIKE '{0}%{1}'", "wpf", ".exe" );

Console.WriteLine ( "Query: {0}", wmiQuery );

ManagementObjectSearcher searcher = new ManagementObjectSearcher ( wmiQuery );
ManagementObjectCollection retObjectCollection = searcher.Get ( );

foreach (ManagementObject retObject in retObjectCollection)
{
    Console.WriteLine ( "[{0}]\tName: {1}", retObject[ "ProcessID" ], retObject["Name"] );
}

Output:

Query: SELECT Name, ProcessID FROM Win32_Process WHERE Name LIKE 'wpf%.exe'
[896] Name: WPFFontCache_v0400.exe

Raillery answered 7/6, 2011 at 11:30 Comment(0)
H
10

To build WMI queries use a free tool from Microsoft known as WMI Code Creator in different programming languages VBS, VB.NET, C#

Download it from http://www.microsoft.com/downloads/en/details.aspx?familyid=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en

Hypoploid answered 7/6, 2011 at 11:40 Comment(2)
@Chad LOL why do you hate it?Elsyelton
@JordanRieger That was 3 years ago, I honestly don't remember...but I'm sure I had a good reason!Waterfront

© 2022 - 2024 — McMap. All rights reserved.