PowerShell 调用以获取 CPU 用法

PowerShell Invoke to get CPU usage

真的很沮丧,因为它似乎非常接近解决方案,但无法让最后一块工作。 我需要使用 C# 获取 CPU 用法。 PerformanceCounter 是不可能的,因为第一次加载需要很长时间。所以尝试使用 PowerShell (System.Management.Automation.dll) 来执行看起来像简单的一行:

(Get-CimInstance Win32_Processor).LoadPercentage

这是 C#:

var cpuUsage = powerShell.AddCommand("Get-CimInstance").AddArgument("Win32_Processor").AddCommand("LoadPercentage").Invoke();

所以你可以看到我正在尝试通过管道传输 LoadPercentage 命令,但它不起作用。

System.Management.Automation.CommandNotFoundException: 'The term 'LoadPercentage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.'

其余代码有效。 任何人都可以在这里发现问题吗? 提前致谢!

这里的问题是 LoadPercentage 是对象的 属性,而不是命令。如果您捕获命令的结果并遍历它的成员,您应该找到您要查找的内容:

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