C# PowerShell调用以获取CPU使用率

C# PowerShell调用以获取CPU使用率,c#,powershell,cpu-usage,C#,Powershell,Cpu Usage,真的很令人沮丧,因为它似乎离解决方案很近,但无法让最后一件工作。 我需要使用C#获取CPU使用率。PerformanceCounter是不可能的,因为第一次加载要花很长时间。因此,尝试使用PowerShell(System.Management.Automation.dll)执行一行简单的命令: (Get-CimInstance Win32_Processor).LoadPercentage 这是C#: 所以您可以看到我正在尝试使用管道LoadPercentage命令,但它不起作用 Syste

真的很令人沮丧,因为它似乎离解决方案很近,但无法让最后一件工作。 我需要使用C#获取CPU使用率。PerformanceCounter是不可能的,因为第一次加载要花很长时间。因此,尝试使用PowerShell(System.Management.Automation.dll)执行一行简单的命令:

(Get-CimInstance Win32_Processor).LoadPercentage
这是C#:

所以您可以看到我正在尝试使用管道
LoadPercentage
命令,但它不起作用

System.Management.Automation.CommandNotFoundException:'术语 “LoadPercentage”未被识别为cmdlet、函数、, 脚本文件或可操作程序。检查名称的拼写,或 如果包含路径,请验证路径是否正确,然后重试 再来一次。”

代码的其余部分工作正常。 有人能在这里指出这个问题吗?
提前谢谢你

这里的问题是
LoadPercentage
是对象的属性,而不是命令。如果捕获命令的结果并遍历其成员,则应找到所需内容:

var results = PowerShell.Create()
    .AddCommand("Get-CimInstance")
    .AddArgument("Win32_Processor")
    .Invoke();
        
foreach (var result in results)
{
    Console.WriteLine(result.Members["LoadPercentage"]?.Value);
}

从示例powershell来看,
LoadPercentage
似乎是一个属性,而不是commandNice,非常感谢!一定要喜欢PS(特别是当你很了解它的时候)。
var results = PowerShell.Create()
    .AddCommand("Get-CimInstance")
    .AddArgument("Win32_Processor")
    .Invoke();
        
foreach (var result in results)
{
    Console.WriteLine(result.Members["LoadPercentage"]?.Value);
}