如何使用PowerShell在SQL Server中收集性能计数器?

时间:2017-09-20 13:07:50

标签: sql-server powershell

我需要使用PowerShell收集SQL Server的性能计数器参数,我需要检查SQL Server参数的阈值。那些应该在一周内运行一次。

我尝试使用PowerShell动态获取所有实例和数据库。现在我试图获取性能计数器并为每个数据库插入一个特定的表,并从该表中检查我需要检查参数阈值的值。

如何做到这一点?

Import-Module "SQLPS" -DisableNameChecking 
$serverInstances = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
foreach ($serverInstance in $serverInstances) {
    $servers = "$env:COMPUTERNAME\$serverInstance"
    $databases = New-Object 'Microsoft.SqlServer.Management.SMO.Server'
    $servers -ErrorAction SilentlyContinue
    $dbs = $databases.Databases  | Select  Name

    foreach ($db in $dbs) {
        $dbname = $db.Name

        $query = "USE [$dbname];

CREATE TABLE [dbo].[PerfmonCounterData]
(
  [ID] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
  [Server] [nvarchar](50) NOT NULL,
  [TimeStamp] [datetime2](0) NOT NULL,
  [CounterGroup] [varchar](200) NULL,
  [CounterName] [varchar](200) NOT NULL,
  [CounterValue] [decimal](18, 5) NULL
);
GO

CREATE PROCEDURE [dbo].[usp_InsertPerfmonCounter]
(
  @xmlString varchar(max)
)
AS
SET NOCOUNT ON;

DECLARE @xml xml;
SET @xml = @xmlString;

INSERT INTO [dbo].[PerfmonCounterData] ([TimeStamp], [Server], [CounterGroup], [CounterName], [CounterValue])
SELECT [Timestamp]
  , SUBSTRING([Path], 3, CHARINDEX('\',[Path],3)-3) AS [Server]
  , SUBSTRING([Path]
  , CHARINDEX('\',[Path],3)+1
  , LEN([Path]) - CHARINDEX('\',REVERSE([Path]))+1 - (CHARINDEX('\',[Path],3)+1)) AS [CounterGroup]
  , REVERSE(LEFT(REVERSE([Path]), CHARINDEX('\', REVERSE([Path]))-1)) AS [CounterName]
  , CAST([CookedValue] AS float) AS [CookedValue]
FROM
    (SELECT
        [property].value('(./text())[1]', 'VARCHAR(200)') AS [Value]
        , [property].value('@Name', 'VARCHAR(30)') AS [Attribute]
        , DENSE_RANK() OVER (ORDER BY [object]) AS [Sampling]
    FROM @xml.nodes('Objects/Object') AS mn ([object]) 
    CROSS APPLY mn.object.nodes('./Property') AS pn (property)) AS bp
PIVOT (MAX(value) FOR Attribute IN ([Timestamp], [Path], [CookedValue]) ) AS ap;
GO"

        Invoke-Sqlcmd -Query $query -ServerInstance $servers -ErrorAction SilentlyContinue

        $counters = @(
            "\Processor(*)\% Processor Time",
            "\processor(_total)\% processor time",
            "\System\Processor Queue Length",
            "\Memory\Available MBytes",
            "\memory\% committed bytes in use",
            "\Paging File(*)\% Usage",
            "\memory\cache faults/sec"
            "\physicaldisk(_total)\% disk time",
            "\physicaldisk(_total)\current disk queue length",
            "\$($serverInstance):Memory Manager\Memory Grants Pending",
            "\$($serverInstance):Memory Manager\Total Server Memory (KB)",
            "\$($serverInstance):Buffer Manager\Page Life Expectancy",
            "\$($serverInstance):General Statistics\User Connections",
            "\$($serverInstance):SQL Statistics\Batch Requests/sec",
            "\$($serverInstance):SQL Statistics\SQL Compilations/sec",
            "\$($serverInstance):SQL Statistics\SQL Re-Compilations/sec"
        )

        $collections = Get-Counter -ComputerName $env:COMPUTERNAME -Counter $counters -SampleInterval 1 -MaxSamples 1

        $sampling = $collections.CounterSamples | Select-Object -Property TimeStamp, Path, Cookedvalue
        $xmlString = $sampling | ConvertTo-Xml -as String
        #dbo.usp_InserPerfmonCounter is the stored procedure that is used to insert collected data to testperf database
        $counterquery = "dbo.usp_InsertPerfmonCounter '$xmlString';"         
        Invoke-Sqlcmd -ServerInstance $env:COMPUTERNAME -Database $dbname -Query $counterquery
    }
}

0 个答案:

没有答案