2011-06-06 130 views
1

谁知道为什么我的查询"select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'"在我的程序C#返回查询不能在C#中工作,但在PowerShell中工作

Column 'Name' does not belong to table Win32_Process 

在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); 
        } 

感谢您的帮助

回答

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"); 
+0

嗨,我改变我的代码,我现在没有现货在Datarow中运行。 我想我有问题,当我尝试行[“名称”] =莫[“名称”]。你知道为什么吗 ? – 2011-06-06 08:57:12

+0

查看我的更新;你没有添加任何列到你的'DataTable'中。 – 2011-06-06 08:57:47

+0

好吧我现在明白了,非常感谢你。你拯救了我的生命! – 2011-06-06 08:59:16

相关问题