Getting CPU Utilisation with PowerShell

PowerShell logoI use the following piece of code in my “Check SMS Server are healthly” PowerShell scripts.  I had a case recently where the SQL Server process decided to use 80% of one CPU.  This script would have detected that problem.

$server_name = “WISEFAQDC”
$percentage_warn = 50

$cpuinfo = Get-WmiObject -ComputerName $server_name Win32_Processor

$count = 0
$cpu_utilisation_total = 0
$cpu_utilisation_average = 0
$cpu_utilisation_maximum_single_processor = 0

foreach ($cpu in $cpuinfo)
    {
    $cpu_utilisation_total = $cpu_utilisation_total + $cpu.LoadPercentage
    $count = $count + 1
    if ($cpu.LoadPercentage -gt $cpu_utilisation_maximum_single_processor)
        {
        $cpu_utilisation_maximum_single_processor = $cpu.LoadPercentage
        }
    }
$cpu_utilisation_average = $cpu_utilisation_total / $count

if ($cpu_utilisation_average -gt $percentage_warn)
    {
    Write-Host "Server: $server_name - CPU load $cpu_utilisation_average %"
    }
if ($cpu_utilisation_maximum_single_processor -gt $percentage_warn)
    {
    Write-Host "Server: $server_name - Single CPU load, highest percentage is: $cpu_utilisation_maximum_single_processor %"
    }

The output is:
Server: WISEFAQDC - CPU load 54 %
Server: WISEFAQDC - Single CPU load, highest percentage is: 82 %

There is a bug though, with Windows 2000 servers always reporting 98% utilisation.  Microsoft released hotfix KB 880086 to fix the problem.

Bookmark and Share