繁体   English   中英

代码在Powershell版本3上有效,但在Powershell 2上无效

[英]Code works on Powershell version 3 but not on Powershell 2

我的以下代码在Powershell版本3上有效,但在Powershell 2上无效。

当我运行时(Get-counter -Counter "\\Processor(_Total)\\% Processor Time" -SampleInterval 1).CounterSamples.CookedValue在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")
    }

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

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

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

@(1).ToBoolean($null)

将在3.0中显示True,但在2.0中会产生错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM