PowerShellを使用してシステムのCPU使用率を確認する方法

PowerShell

定期的にCPU使用率をチェックする

# 5秒ごとにCPU使用率を取得し表示する
while($true) {
    $cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
    Write-Host "CPU使用率:$($cpuUsage.CounterSamples[0].CookedValue) %"
    Start-Sleep -Seconds 5
}

コードの説明
Get-Counterは、システムやアプリケーションのパフォーマンスデータを取得する非常に強力なコマンドレット
\Processor(_Total)\% Processor Timeは、全CPUの平均使用率を示すパス

高いCPU使用率が継続したら警告を出す

# CPU使用率が80%以上が5回続いたら警告を出す
$count = 0
while($true) {
    $cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
    if($cpuUsage.CounterSamples[0].CookedValue -ge 80) {
        $count++
    } else {
        $count = 0
    }

    if($count -ge 5) {
        Write-Host "警告:CPU使用率が高いです"
    }

    Start-Sleep -Seconds 5
}

ログファイルにCPU使用率を保存する

# CPU使用率をログファイルに保存する
while($true) {
    $cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
    Add-Content -Path "C:\path\to\log.txt" -Value "CPU使用率:$($cpuUsage.CounterSamples[0].CookedValue) %"
    Start-Sleep -Seconds 5
}

コメント