简体   繁体   中英

Code works on Powershell version 3 but not on Powershell 2

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

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

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