I am using below Powershell code to check the instant CPU utilization in my Windows Server (SQL Server Database boxes).
What I am trying to do get the accurate results of CPU utilization . But the below code does seems to be helping , could anyone aware of this please help. Even using the counter values doesn't give me the accurate values , please help.
Function Get-Cpu {
[CmdletBinding()]
Param (
[parameter(Mandatory, ValueFromPipeline)]
[String[]]$ServerInstance,
[parameter(Mandatory = $true)] $NumOfSessions
)
foreach($i in $ServerInstance){
Get-Counter -ComputerName $i -Counter "\Process(*)\% Processor Time" -ErrorAction SilentlyContinue `
| select -ExpandProperty CounterSamples `
| where {$_.Status -eq 0 } `
| sort CookedValue -Descending `
| select @{N = "SQLInstance";e={$i}} , TimeStamp,
@{N="Name";E={
$friendlyName = $_.InstanceName
try {
$procId = [System.Diagnostics.Process]::GetProcessesByName($_.InstanceName)[0].Id
$proc = Get-WmiObject -Query "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId=$procId"
$procPath = ($proc | where { $_.ExecutablePath } | select -First 1).ExecutablePath
$friendlyName = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($procPath).FileDescription
} catch { }
$friendlyName
}},
@{N="CPU";E={(($_.CookedValue/100/$env:NUMBER_OF_PROCESSORS)/100).ToString("P")}} -First $NumOfSessions |Format-Table -AutoSize
}
}
Get-Cpu