微调Get-Counter脚本以加快执行速度

时间:2014-08-18 03:22:52

标签: powershell cpu-usage performancecounter w3wp

下面是我的脚本,用于获取各个w3wp.exe应用程序池的进程利用率,问题是每次迭代大约需要2秒,大约有25个应用程序池。你能不能帮我调整下面的脚本以便更快地执行。

    gwmi win32_process -filter 'name="w3wp.exe"' | % {
    $name=$_.name
    $cmd = $pattern.Match($_.commandline).Groups[1].Value
    $procid = $_.ProcessId
    $tmp = (Get-Counter "\Process(*)\ID Process").CounterSamples | Where-Object       {$_.CookedValue -eq $procid} | select -expand Path
    $calc = [regex]::match($tmp,'\(([^\)]+)\)').Groups[1].Value
    $cooked = (Get-Counter "\Process($calc)\% Processor Time").CounterSamples | Where-Object {$_.InstanceName -notlike '_total'} | select -expand CookedValue
    $cpuper = [Math]::Round( ($cooked/2), 0)
    echo $cpuper
    }

1 个答案:

答案 0 :(得分:2)

看起来Get-Counter的最短采样时间为1秒。每次通话最短执行时间为1秒。您最好的选择是将所有计数器放在前面,然后寻找您感兴趣的计数器。

这就像你在做什么一样。它在表中打印进程ID和%处理器时间。

$proc = 'w3wp'
$samples = get-counter '\Process($proc*)\ID Process', '\Process($proc*)\% Processor Time' | select -expand countersamples 
$samples | group { Split-Path $_.Path } | ft @{ N='ID'; E={$_.Group[0].CookedValue} }, @{ N='% Processor'; E={[Math]::Round($_.Group[1].CookedValue/2, 0)} }