2014-02-06 30 views
0

我下面的代碼工作在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") 
    } 
+1

請更具體地說明它如何「不起作用」。是否有錯誤,輸出錯誤或其他意外情況? –

+1

「這不起作用」不是一個合適的問題描述。什麼具體不起作用?你有什麼錯誤(如果有的話)?如果你在這裏需要幫助,你需要在描述你遇到的問題和你提出的問題中具體說明。 –

+0

好吧..當我運行(獲取計數器 - 計數器\處理器(_Total)\%處理器時間「-SampleInterval 1).CounterSamples.CookedValue在v3我得到輸出,但不是在v2中輸出 。 –

回答

3

似乎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

謝謝!有用 :) –

相關問題