Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - How to construct WMI query

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}]Name: {1}", retObject[ "ProcessID" ], retObject["Name"] );
}

Output:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...