0

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")
    }
3
  • 1
    Please be more specific about how it "doesn't work". Is there an error, incorrect output, or something else unexpected? Commented Feb 6, 2014 at 17:48
  • 1
    "This doesn't work" is not a suitable problem description. What specifically doesn't work? What errors (if any) are you getting? If you want help here, you need to be specific in describing the problem you're having and in the question you're asking. Commented Feb 6, 2014 at 17:50
  • Ok.. when I run (Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1).CounterSamples.CookedValue on v3 I get output but not in v2. Commented Feb 6, 2014 at 17:54

1 Answer 1

3

It seems that CounterSamples is actually an array, so it should be

(Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1).CounterSamples[0].CookedValue

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:

@(1).ToBoolean($null)

will print True in 3.0 but yields an error in 2.0.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.