Ash Ketchum
Ash Ketchum

Reputation: 15

Using 'LoadPercentage' for performance monitoring

I am trying to use the value retrieved from the WMI-Object to set a criteria for performance monitoring.

Here are the codes that I have used:

$CPULoad = Get-WMIObject -computername $computer win32_processor | `
           Measure-Object -Property LoadPercentage -Average | `
           Select Average

$WarningCPU = ($CPULoad * 0.8)

If ($CPULoad -ge $WarningCPU){
    [System.Windows.Forms.MessageBox]::Show("CPU Usage is over 80%","Warning","Ok","Warning")
}

I want to keep the cpu usage at a limit of 80% by using these codes, however this came up:

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Multiply'.

Cannot compare "@{Average=14}" to "50" because the objects are not the same type or the object "@{Average=14}" does not implement "IComparable".

Is there a way to make the values "comparable" so that the messagebox will show up when cpu usage of user hits >80% ?

Upvotes: 0

Views: 320

Answers (1)

kim
kim

Reputation: 3421

Like @arco444 said, use | Select -ExpandProperty Average to solve your problem. This will make your error go away.

I just want to expand on the issue and the importance of types.

Types

The problem you are having in your code is that the Average property that you get back from Measure-Object is not a "number". It looks like one, but the type is not something you can use for calculations.

Remember, PowerShell cmdlets return objects and place them in the pipeline. They might look like numbers and text, but might be something entirely different.

You can check the properties and types of what PowerShell cmdlets return by piping their result through the cmdlet Get-Member, or if you prefer its alias gm.

Running

Get-WMIObject -computername $computer win32_processor | `
           Measure-Object -Property LoadPercentage -Average | `
           Select Average | `
           Get-Member

will tell you that Average has type

TypeName: Selected.Microsoft.PowerShell.Commands.GenericMeasureInfo

GenericMeasureInfo can't be used calculations.

However, it will tell you there is a property named Average of type double.

Double is good, that you can use for calculations :)

Extracting properties using Select-Object -ExpandProperty

Problem now is that it must be extracted from the object. This is where Select -ExpandObject comes into play.

It takes a property and extracts it from the parent object, preserving its type.

Running

Get-WMIObject -computername $computer win32_processor | `
           Measure-Object -Property LoadPercentage -Average | `
           Select -ExpandProperty Average | `
           Get-Member

tells you the type now is

TypeName: System.Double

Now calculations work :)

Upvotes: 1

Related Questions