代码适用于PowerShell的3版本,但不是在PowerShell的2
问题描述:
我下面的代码工作在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
的区别似乎是Powershell的3.0似乎处理含有一个单一的项目LIK阵列e用于调用方法和属性的项目,例如:
@(1).ToBoolean($null)
将在3.0中打印True,但在2.0中产生错误。
+0
谢谢!有用 :) –
请更具体地说明它如何“不起作用”。是否有错误,输出错误或其他意外情况? –
“这不起作用”不是一个合适的问题描述。什么具体不起作用?你有什么错误(如果有的话)?如果你在这里需要帮助,你需要在描述你遇到的问题和你提出的问题中具体说明。 –
好吧..当我运行(获取计数器 - 计数器\处理器(_Total)\%处理器时间“-SampleInterval 1).CounterSamples.CookedValue在v3我得到输出,但不是在v2中输出 。 –