简体   繁体   中英

PowerShell Invoke to get CPU usage

Really frustrating because it seems to be so close to solution but can't get the last piece working. I need to get CPU usage using C#. PerformanceCounter is out the question because it takes forever to load the first time. So trying to use PowerShell (System.Management.Automation.dll) to execute what looks like a simple line:

(Get-CimInstance Win32_Processor).LoadPercentage

This is C#:

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

So you can see I'm trying to pipe LoadPercentage command but it won't work.

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.'

The rest of code works. Can anyone please spot the issue here? Thank you in advance!

The issue here is that LoadPercentage is a property of the object, not a command. If you capture the result of the command and iterate through it's members, you should find what you're looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM