Shell script to get cpu Iinfo

SVA 116 Reputation points
2024-06-02T12:08:29.5033333+00:00

Hi

Is there any PowerShell script to retrieve the CPU usage of SQL Server and system idle

Thanks

SQL Server Other
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 49,640 Reputation points MVP Volunteer Moderator
    2024-06-02T12:31:59.1533333+00:00

    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


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.