powershell 我如何循环访问get-counter的结果来做出决定?

jgwigjjp  于 2023-02-04  发布在  Shell
关注(0)|答案(3)|浏览(143)

我试图在5分钟内获取以下计数器。如果它连续5次返回100,我希望收到电子邮件。

get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 60 -MaxSamples 5

我试着把这段代码赋给一个变量,例如:

$value = get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 60 -MaxSamples 5

if($value eq 100)
{
  $counter = $counter + 1
}

if($counter > 4)
{
"send an email"
}

问题是我不能得到实际的计数器值来赋值给$value变量,而且我希望计数器在每次代码触发时递增(在它达到maxsamples值之前)。
任何帮助都将不胜感激。

kadbb459

kadbb4591#

Get-Counter返回一个Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet类型的数组,因此必须按如下方式处理它:
一个更通用的解决方案:

$sampleInterval = 60 # in seconds
$samples = 50 # samples taken
$inRowSamples = 5 # 5 samples in a row
$shouldntExceed = 0.95 # 95%

$values = get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval $sampleInterval -MaxSamples $samples

$count = 0
foreach ($value in $values)
{
    if ($value.CounterSamples[0].CookedValue -gt $shouldntExceed)
    {
        $count++;
    }
    else
    {
        $count = 0;
    }

    if ($count -ge $inRowSamples)
    {
        # send email
        break;
    }
}
lc8prwob

lc8prwob2#

我觉得你想要这样的东西:

$value = get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5
$Total = $Value | % { $_.CounterSamples[0].CookedValue } | Measure -Sum;

if ($Total.Sum -ge 490) {
    # Total CPU usage was 490+
}

或者,如果要在百分比上下文中执行此操作,请执行以下操作:

$value = get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5
$Total = $Value | % { $_.CounterSamples[0].CookedValue } | Measure -Average;

if ($Total.Average -ge 95) {
    # Total CPU usage was 95%+
}
qv7cva1a

qv7cva1a3#

试试这个:

$maxCount = 5;
$maxValue = 100;
$count = 0;
get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 | %{

    if($_.CounterSamples[0].CookedValue -ge $maxValue){
        $count++;
    }
    #handling the n times in a row condition
    else{
        $count=0
    }
    if($count -eq $maxCount){
        write-host "exceeded"
        #send email
        break
    }

}

由于我们使用的是管道,上面将发送电子邮件,只要你有5个连续的值大于或等于100。

相关问题