我想查詢根\ CIMV2命名空間內的所有WMI類的名稱。有沒有辦法使用PowerShell命令在C#中檢索這些信息?在C#中的Powershell命令#
7
A
回答
5
伴隨基思的做法的線
using System;
using System.Management.Automation;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var script = @"
Get-WmiObject -list -namespace root\cimv2 | Foreach {$_.Name}
";
var powerShell = PowerShell.Create();
powerShell.AddScript(script);
foreach (var className in powerShell.Invoke())
{
Console.WriteLine(className);
}
}
}
}
7
我不知道你爲什麼提到PowerShell;你可以在純C#和WMI(即System.Management
命名空間)中執行此操作。
要獲得所有WMI類的列表,使用SELECT * FROM Meta_Class
查詢:
using System.Management;
...
try
{
EnumerationOptions options = new EnumerationOptions();
options.ReturnImmediately = true;
options.Rewindable = false;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\cimv2", "SELECT * FROM Meta_Class", options);
ManagementObjectCollection classes = searcher.Get();
foreach (ManagementClass cls in classes)
{
Console.WriteLine(cls.ClassPath.ClassName);
}
}
catch (ManagementException exception)
{
Console.WriteLine(exception.Message);
}
3
你可能會希望只使用System.Management命名空間像海倫回答,但你也可以在主機的PowerShell的應用。見http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx
3
就我個人而言,我會用海倫的方法,並取消對PowerShell的依賴。這就是說,這裏是你將如何在C#代碼此使用PowerShell來獲取所需的信息:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
namespace RunspaceInvokeExp
{
class Program
{
static void Main()
{
using (var invoker = new RunspaceInvoke())
{
string command = @"Get-WmiObject -list -namespace root\cimv2" +
" | Foreach {$_.Name}";
Collection<PSObject> results = invoker.Invoke(command);
var classNames = results.Select(ps => (string)ps.BaseObject);
foreach (var name in classNames)
{
Console.WriteLine(name);
}
}
}
}
}
4
只是要注意,可用的工具允許您創建,運行和保存用PowerShell編寫的WMI腳本,PowerShell Scriptomatic工具可從Microsoft TechNet網站下載。
使用此工具,您可以探索root \ CIMV2或任何其他WMI名稱空間內的所有WMI類。
相關問題
- 1. C#將命令傳入PowerShell
- 2. 運行命令在PowerShell中
- 3. 在C#上執行PowerShell命令行
- 4. PowerShell中的IPython Shell命令
- 5. PHP PowerShell命令
- 6. 在Windows中等效的Unix命令Powershell
- 7. 在C#中的Powershell返回命令輸出
- 8. 使用C#執行Powershell命令(azureVM)
- 9. Powershell命令通過C#代碼
- 10. 使用C調用Powershell命令#
- 11. 存儲:C#相當於PowerShell命令
- 12. curl -c命令powershell - Cookie文件位置
- 13. 缺少PowerShell命令
- 14. 超時powershell命令
- 15. Powershell遠程命令
- 16. Powershell Get-ChildItem命令
- 17. 結合powershell命令
- 18. Powershell命令失敗
- 19. 運行PowerShell命令
- 20. System 32 powershell命令
- 21. 在命令行和Windows PowerShell中Imagemagick命令
- 22. 多PowerShell命令需要從命令行
- 23. 在powershell腳本中執行sql命令
- 24. 輸出ssh命令在PowerShell中
- 25. 在PowerShell中運行遠程cmd命令
- 26. 在PowerShell中執行Subst命令
- 27. 推出的PowerShell命令與
- 28. 的PowerShell調用命令
- 29. 如何將Powershell命令一起在C#中管理
- 30. 在C#中使用PowerShell運行命令時訪問被拒絕
這很好用。謝謝您的幫助。 – Sanch01R 2009-12-21 11:09:17