代码适用于Powershell版本3,但不适用于Powershell 2

时间:2014-02-06 17:40:49

标签: powershell powershell-v2.0 powershell-v3.0

我的下面的代码适用于Powershell版本3,但不适用于Powershell 2。

当我在v3上运行(Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1).CounterSamples.CookedValue时,我得到输出但不是在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")
    }

1 个答案:

答案 0 :(得分:3)

看起来CounterSamples实际上是一个数组,所以它应该是

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

差异似乎是Powershell 3.0似乎将包含单个项目的数组视为调用方法和属性的项目,例如:

@(1).ToBoolean($null)

将在3.0中打印True,但在2.0中会产生错误。