我的下面的代码适用于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")
}
答案 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中会产生错误。