代码可以在PowerShell版本3上运行,但不能在PowerShell 2上运行 [英] Code works on Powershell version 3 but not on Powershell 2

查看:27
本文介绍了代码可以在PowerShell版本3上运行,但不能在PowerShell 2上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的以下代码可以在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")
    }

推荐答案

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

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

不同之处在于Powershell3.0似乎为了调用方法和属性而处理包含单个项的数组,例如:

@(1).ToBoolean($null)

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

这篇关于代码可以在PowerShell版本3上运行,但不能在PowerShell 2上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆