Try the following
# Function to get SQL Server CPU usage and system idle time
function Get-SqlServerCpuUsage {
param (
[string]$SqlInstance = "MSSQLSERVER" # Default SQL Server instance name
)
# Get the process ID of the SQL Server instance
$sqlProcess = Get-Process -Name "sqlservr" | Where-Object { $_.Id -eq (Get-Service -Name $SqlInstance).Id }
if ($sqlProcess) {
$sqlProcessId = $sqlProcess.Id
# Get the CPU usage of the SQL Server instance
$sqlCpuUsage = Get-Counter "\Process(sqlservr*)\% Processor Time" | Select-Object -ExpandProperty CounterSamples | Where-Object { $_.InstanceName -eq $sqlProcessId }
$sqlCpuUsageValue = ($sqlCpuUsage.CookedValue / (Get-Counter -Counter "\Processor(_Total)\% Processor Time").CounterSamples[0].CookedValue) * 100
# Get the system idle time
$systemIdle = Get-Counter "\Processor(_Total)\% Idle Time"
$systemIdleValue = $systemIdle.CounterSamples[0].CookedValue
# Output the results
[PSCustomObject]@{
SqlCpuUsage = "{0:N2}" -f $sqlCpuUsageValue
SystemIdle = "{0:N2}" -f $systemIdleValue
}
} else {
Write-Error "SQL Server instance '$SqlInstance' is not running."
}
}
# Example usage
Get-SqlServerCpuUsage
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin