1

任何人都知道为什么我的查询"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);
                    }

谢谢你的帮助

4

1 回答 1

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");
于 2011-06-06T08:50:02.423 回答