c# - 在 C# 中模仿这个非常简单的 powershell 命令
问题描述
试图模仿Get-CimInstance CIM_ManagedSystemElement
C# 中的命令
string NamespacePath = "\\\\.\\Root\\CIMv2";
string ClassName = "CIM_ManagedSystemElement";
//Create ManagementClass
ManagementClass oClass = new ManagementClass(NamespacePath + ":" + ClassName);
//Get all instances of the class and enumerate them
foreach (ManagementObject oObject in oClass.GetInstances())
{
//access a property of the Management object
Console.WriteLine("Caption : {0}", oObject["Caption"]);
}
可悲的是,这没有按预期工作,想得到一些帮助
谢谢
解决方案
我也无法让您的代码正常工作,但与此同时,如果您需要解决方法,您可以使用我根据一些在线文档编写的这个简单程序在 C# 中使用 PowerShell API。它会给你一个你正在寻找的输出。您应该可以访问 OutputCollection_DataAdded 中的所有属性,因此如果您需要的不仅仅是 Caption,您可以在此处获取它。此外,在执行结束时有一个 foreach() 循环,如果您需要对其执行某些操作,它将包含整个输出集合。执行速度非常慢,所以我不得不让它异步工作。
static void Main(string[] args)
{
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Get-CimInstance");
ps.AddParameter("-ClassName", "CIM_ManagedSystemElement");
var outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += OutputCollection_DataAdded;
// invoke execution on the pipeline (collecting output)
var async = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
// do something else until execution has completed.
// this could be sleep/wait, or perhaps some other work
while (async.IsCompleted == false)
{
Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(1000);
// might want to place a timeout here...
}
Console.WriteLine("Execution has stopped. The pipeline state: " + ps.InvocationStateInfo.State);
// loop through each output object item
foreach (PSObject outputItem in ps.EndInvoke(async))
{
// if null object was dumped to the pipeline during the script then a null
// object may be present here. check for null to prevent potential NRE.
if (outputItem != null)
{
//TODO: do something with the output item
// outputItem.BaseOBject
}
}
Console.Read();
}
}
private static void OutputCollection_DataAdded(object sender, DataAddedEventArgs e)
{
if (sender is PSDataCollection<PSObject>)
{
var output = (PSDataCollection<PSObject>)sender;
// Handle the output item here
var caption = output.Last().Properties["Caption"];
if (caption != null)
{
Console.WriteLine($"Caption: {caption.Value}");
}
}
}
推荐阅读
- python - 如何使用 selenium python 从网页中单独获取过滤后的项目?
- c - 从C中的文件中读取多个整数行
- algorithm - 50 个学生小组的功能或循环结构是什么。这样他们在将他们分配到不同的组时就不会面对。怎么解决?
- javascript - paytm JS Checkout 与 vue JS 前端的集成
- python - 如何从该图像中裁剪手机?
- javascript - d3 图表中的针值以十进制格式显示
- python - 如何在本地系统上使用烧瓶部署机器学习模型
- python - 有没有办法在循环中使用 np.save(或 np.savetxt)?我有一个非常大的数据集,因此无法将这些部分收集到一个大数组中
- python - 如何在 selenium python 中单击 2 个 div 内的按钮?
- angular - 如何让我的 ngModel 在我的 ng-template 中自动工作?