查询不适用于c#,但适用于powershell

时间:2011-06-06 08:42:03

标签: c# process win32-process

任何人都知道为什么我的查询"select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'"会返回

 Column 'Name' does not belong to table Win32_Process

在我的程序C#中。

执行时在powershell中

Get-WmiObject -query "select Name, ProcessID, Caption from win32_process"

这是有效的!

   String queryString = "select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'";
                SelectQuery query = new SelectQuery(queryString);

                ConnectionOptions options = new ConnectionOptions();
                options.Authentication = System.Management.AuthenticationLevel.PacketPrivacy;


                ManagementScope scope = new System.Management.ManagementScope("\\root\\cimv2");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                try
                {
                    ManagementObjectCollection processes = searcher.Get();
                    DataTable result = new DataTable();
                    foreach (ManagementObject mo in processes)
                    {
                        DataRow row = result.NewRow();
                        if (mo["Name"] != null)
                            row["Name"] = mo["Name"].ToString();
                        row["ProcessId"] = Convert.ToInt32(mo["ProcessId"]);
                        if (mo["Caption"] != null)
                            row["Caption"] = mo["Caption"].ToString();
                        result.Rows.Add(row);
                    }

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

此代码:

const string queryString = "SELECT Name, ProcessID, Caption FROM Win32_Process";

var scope = new ManagementScope(@"\root\cimv2");
var query = new ObjectQuery(queryString);
var searcher = new ManagementObjectSearcher(scope, query);
var objectCollection = searcher.Get();

foreach (var o in objectCollection)
{
    Console.WriteLine("{0} {1} {2}", o["Name"], o["ProcessID"], o["Caption"]);
}

......对我来说很好。你的代码究竟是如何工作的?

(顺便说一句,你似乎没有对options做任何事情。)

<强>更新

实际上是抱怨,因为您没有在DataTable中设置列。我认为你已经削减了你的榜样太多了。您的DataTable被称为“Win32_Process”,是吗?如果我称我为“阿尔伯特”:

var table = new DataTable("Albert");

我得到Column 'Name' does not belong to table Albert.

您需要执行以下操作:

var table = new DataTable("Albert");
table.Columns.Add("Name");
table.Columns.Add("ProcessID", typeof(int));
table.Columns.Add("Caption");