My below code works on Powershell version 3 but not on Powershell 2.
when I run (Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1).CounterSamples.CookedValue
on v3 I get output but not in v2
[System.Int32] $NumberOfSamples = 3
[System.Int32] $FreeCPUThreshold = 10
[System.Double[]] $CPUArray = @()
[System.Int32] $LoopCounter = 1
while ($LoopCounter -lt $NumberOfSamples)
{
$CPUArray += (Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1).CounterSamples.CookedValue
$LoopCounter++
}
$CalculatedUsedCPU = [System.Math]::Floor( ($CPUArray | Measure-Object -average).Average)
if ($CalculatedUsedCPU -gt $FreeCPUThreshold)
{
Write-Host ("Free CPU threshold (" + $FreeCPUThreshold + " %) was hit on machine: `"" + $TargetHostname + "`", with value of: " + $CalculatedUsedCPU + " %.")
}
else
{
Write-Host ("Free CPU threshold (" + $FreeCPUThreshold + " %) was hit on machine: `"" + $TargetHostname + "`", with value of: " + $CalculatedUsedCPU + " %." , "UNDER CONTROL")
}
It seems that CounterSamples is actually an array, so it should be
The difference appears to be that Powershell 3.0 seems to treat an array containing a single item like the item for purposes of invoking methods and properties, for example:
will print True in 3.0 but yields an error in 2.0.