运维联盟俱乐部

 找回密码
 立即注册
查看: 2497|回复: 0

SQL Server Health Check Script with Powershell

[复制链接]
  • TA的每日心情
    开心
    2023-8-9 11:05
  • 发表于 2020-1-16 15:22:09 | 显示全部楼层 |阅读模式
    1. param(
    2. [string]$servernames
    3. )Add-PSSnapin SqlServerCmdletSnapin110
    4. Add-PSSnapin SqlServerProviderSnapin110
    5. cls
    6. write-host $servernames
    7. $starttime = Get-Date
    8. write-host $starttime
    9. foreach($servername in $servernames)
    10. {write-host Starting Server $servername
    11. $dataSource = $servername
    12. $database = "master"
    13. $TableHeader = "SQL Server Health Check Report"
    14. $path = "S:\Health_Check\Reports"
    15. $name = $dataSource -replace "\","_"
    16. $OutputFile_new = $path + $name + '.html' ##The file location
    17. $a = "<style>"
    18. $a = $a + "BODY{background-color:white;}"
    19. $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
    20. $a = $a + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;;background-color:thistle}"
    21. $a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
    22. $a = $a + "</style>"
    23. $colorTagTable = @{
    24. Stopped = ' bgcolor="RED">Stopped<';
    25. Running = ' bgcolor="Green">Running<';
    26. OFFLINE = ' bgcolor="RED">OFFLINE<';
    27. ONLINE = ' bgcolor="Green">ONLINE<'
    28. "ALL DATABASES ARE" = ' bgcolor="Green">ALL DATABASES ARE<'
    29. "ALL Databases has been" = '
    30. bgcolor="Green">ALL Databases has been<';
    31. "backup" = ' bgcolor="Green">backup<';
    32. "in Last 24 Hours" = ' bgcolor="Green">in Last 24 Hours<';
    33. "No Job Failed in Last 24 Hours" = '
    34. bgcolor="Green">No Job Failed in Last 24 Hours<';
    35. "Error Log" = ' bgcolor="Green">Error Log<';
    36. "check did not find out anything major" = '
    37. bgcolor="Green">check did not find out anything major<';
    38. "but will still advise to please verify manually" = '
    39. bgcolor="Green">but will still advise to please verify manually<';
    40. "Server Might Have Memory Issue" = '
    41. bgcolor="Red">Server Might Have Memory Issue<';
    42. }
    43. ##Create a string variable with all our connection details
    44. $connectionDetails = "Provider=sqloledb; " + "Data Source=$dataSource;
    45. " + "Initial Catalog=$database; " + "Integrated Security=SSPI;"
    46. ##**************************************
    47. ##Calculating SQL Server Information
    48. ##**************************************
    49. $sql_server_info = "select @@servername as [SQLNetworkName],
    50. CAST( SERVERPROPERTY('MachineName') AS NVARCHAR(128)) AS [MachineName],
    51. CAST( SERVERPROPERTY('ServerName')AS NVARCHAR(128)) AS [SQLServerName],
    52. CAST( SERVERPROPERTY('IsClustered') AS NVARCHAR(128)) AS [IsClustered],
    53. CAST( SERVERPROPERTY('ComputerNamePhysicalNetBIOS')AS NVARCHAR(128)) AS [SQLService_Current_Node],
    54. serverproperty('edition') as [Edition],
    55. serverproperty('productlevel') as [Servicepack],
    56. CAST( SERVERPROPERTY('InstanceName') AS NVARCHAR(128)) AS [InstanceName],
    57. SERVERPROPERTY('Productversion') AS [ProductVersion],@@version as [Serverversion]"
    58. ##Connect to the data source using the connection details and T-SQL command we provided above,
    59. ##and open the connection
    60. $connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    61. $command1 = New-Object System.Data.OleDb.OleDbCommand $sql_server_info,$connection
    62. $connection.Open()
    63. ##Get the results of our command into a DataSet object, and close the connection
    64. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command1
    65. $dataSet1 = New-Object System.Data.DataSet
    66. $dataAdapter.Fill($dataSet1)
    67. $connection.Close()
    68. ##Return all of the rows and pipe it into the ConvertTo-HTML cmdlet,
    69. ##and then pipe that into our output file
    70. $frag1 = $dataSet1.Tables | Select-Object -Expand Rows |select -Property SQLNetworkName,
    71. MachineName,SQLServerName,IsClustered,SQLService_Current_Node,Edition,Servicepack,InstanceName,
    72. ProductVersion,Serverversion | ConvertTo-HTML -AS Table -Fragment
    73. -PreContent '<h2>SQL Server Info</h2>'|Out-String
    74. write-host $frag1
    75. ##**************************************
    76. ##SQL Server AGent Information Collection
    77. ##**************************************
    78. $sqlserverAgent = "
    79. IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#sql_agent_state'))
    80. BEGIN
    81. drop table
    82. END
    83. declare @sql_agent_service varchar(128),@state_sql_agent varchar(20)
    84. create table
    85. insert into
    86. --select service_name as ServiceName, state as Status from
    87. select service_name as ServiceName, replace(state,'.','') as Status from
    88. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    89. $command2 = New-Object System.Data.OleDb.OleDbCommand $sqlserverAgent,$connection
    90. $connection.Open()
    91. ##Get the results of our command into a DataSet object, and close the connection
    92. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command2
    93. $dataSet2 = New-Object System.Data.DataSet
    94. $dataAdapter.Fill($dataSet2)
    95. $connection.Close()
    96. $frag2 = $dataSet2.Tables | Select-Object -Expand Rows| Select -Property ServiceName,
    97. Status|ConvertTo-HTML -AS Table -Fragment
    98. -PreContent '<h2>SQL Server Agent Status</h2>'|Out-String
    99. $colorTagTable.Keys | foreach { $frag2 = $frag2 -replace ">$_<",($colorTagTable.$_) }
    100. write-host $frag2
    101. ##**************************************
    102. ##Database states
    103. ##**************************************
    104. $SQLServerDatabaseState = "
    105. IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tmp_database'))
    106. BEGIN
    107. drop table
    108. END
    109. declare @count int
    110. declare @name varchar(128)
    111. declare @state_desc varchar(128)
    112. select @count = COUNT(*) from sys.databases where state_desc not in ('ONLINE','RESTORING')
    113. create table
    114. if @count > 0
    115. begin
    116. Declare Cur1 cursor for select name,state_desc from sys.databases
    117. where state_desc not in ('ONLINE','RESTORING')
    118. open Cur1
    119. FETCH NEXT FROM Cur1 INTO @name,@state_desc
    120. WHILE @@FETCH_STATUS = 0
    121. BEGIN
    122. insert into
    123. FETCH NEXT FROM Cur1 INTO @name,@state_desc
    124. END
    125. CLOSE Cur1
    126. DEALLOCATE Cur1
    127. end
    128. else
    129. begin
    130. insert into
    131. end
    132. select name as DBName ,state_desc as DBStatus from
    133. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    134. $command3 = New-Object System.Data.OleDb.OleDbCommand $SQLServerDatabaseState,$connection
    135. $connection.Open()
    136. ##Get the results of our command into a DataSet object, and close the connection
    137. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command3
    138. $dataSet3 = New-Object System.Data.DataSet
    139. $dataAdapter.Fill($dataSet3)
    140. $connection.Close()
    141. $frag3 = $dataSet3.Tables | Select-Object -Expand Rows |Select -Property DBName,DBStatus |
    142. ConvertTo-HTML -AS Table -Fragment -PreContent '<h2>SQLServer Databases State</h2>'|Out-String
    143. $colorTagTable.Keys | foreach { $frag3 = $frag3 -replace ">$_<",($colorTagTable.$_) }
    144. write-host $frag3
    145. ##**************************************
    146. ##SQL Job Status
    147. ##**************************************
    148. $SQLJob = "
    149. declare @count int
    150. select @count = count(1) from msdb.dbo.sysjobs as sj
    151. join msdb.dbo.sysjobhistory as sjh on sj.job_id = sjh.job_id
    152. where sj.enabled != 0
    153. and sjh.sql_message_id > 0
    154. and sjh.run_date > CONVERT(char(8), (select dateadd (day,(-1), getdate())), 112)
    155. and sjh.Step_id <= 1
    156. if (@count >= 1)
    157. begin
    158. select distinct sj.name as SQLJobName
    159. from msdb.dbo.sysjobs as sj
    160. join msdb.dbo.sysjobhistory as sjh on sj.job_id = sjh.job_id
    161. where sj.enabled != 0
    162. and sjh.sql_message_id > 0
    163. and sjh.run_date > CONVERT(char(8), (select dateadd (day,(-1), getdate())), 112)
    164. and sjh.Step_id <= 1
    165. order by name
    166. end
    167. else
    168. begin
    169. Select 'No Job Failed in Last 24 Hours' as SQLJobName
    170. end
    171. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    172. $command4 = New-Object System.Data.OleDb.OleDbCommand $SQLJob,$connection
    173. $connection.Open()
    174. ##Get the results of our command into a DataSet object, and close the connection
    175. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command4
    176. $dataSet4 = New-Object System.Data.DataSet
    177. $dataAdapter.Fill($dataSet4)
    178. $connection.Close()
    179. $frag4 = $dataSet4.Tables | Select-Object -Expand Rows |select -Property SQLJobName |
    180. ConvertTo-HTML -AS Table -Fragment -PreContent
    181. '<h2>SQLServer SQL Job failed in last 24 Hours</h2>'|Out-String
    182. $colorTagTable.Keys | foreach { $frag4 = $frag4 -replace ">$_<",($colorTagTable.$_) }
    183. write-host $frag4
    184. ##**************************************
    185. ##Database Backup in Last 24 Hours
    186. ##**************************************
    187. $SQLServerDatabaseBackup = "
    188. declare @backupcount int
    189. select @backupcount = count(1)
    190. from sys.databases
    191. where state != 6
    192. and name not like 'Tempdb%'
    193. and name not in
    194. (select database_name
    195. from msdb.dbo.backupset as bkupset
    196. join msdb.dbo.backupmediafamily as bkupmedf on bkupset.media_set_id = bkupmedf.media_set_id
    197. where type in ('D','I')
    198. and backup_start_date > (CONVERT(datetime,getdate()) - 1)
    199. )if (@backupcount >= 1)
    200. begin
    201. select name as DBName, State_Desc as DBStatus,'Backup Not happened' as DBComments from sys.databases
    202. where state != 6
    203. and name not like 'Tempdb%'
    204. and name not in
    205. (select database_name
    206. from msdb.dbo.backupset as bkupset
    207. join msdb.dbo.backupmediafamily as bkupmedf on bkupset.media_set_id = bkupmedf.media_set_id
    208. where type in ('D','I')
    209. and backup_start_date > (CONVERT(datetime,getdate()) - 1)
    210. )order by 1
    211. end
    212. else
    213. begin
    214. Select 'ALL Databases has been' as DBName,
    215. 'backup' as DBStatus ,'in Last 24 Hours' as DBComments
    216. end
    217. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    218. $command5 = New-Object System.Data.OleDb.OleDbCommand $SQLServerDatabaseBackup,$connection
    219. $connection.Open()
    220. ##Get the results of our command into a DataSet object, and close the connection
    221. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command5
    222. $dataSet5 = New-Object System.Data.DataSet
    223. $dataAdapter.Fill($dataSet5)
    224. $connection.Close()
    225. $frag5 = $dataSet5.Tables | Select-Object -Expand Rows |select -property DBName,
    226. DBStatus,DBComments | ConvertTo-HTML -AS Table -Fragment
    227. -PreContent '<h2>SQLServer Database Backup status in Last 24 Hours</h2>'|Out-String
    228. $colorTagTable.Keys | foreach { $frag5 = $frag5 -replace ">$_<",($colorTagTable.$_) }
    229. write-host $frag5
    230. ##**************************************
    231. ##SQL Server ErrorLog
    232. ##**************************************
    233. $SQLServerErrorlog = "
    234. declare @errorlogcount int
    235. IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#errorlog'))
    236. BEGIN
    237. DROP TABLE
    238. END
    239. create table
    240. insert into
    241. select @errorlogcount = count(*) from
    242. where date_time > (CONVERT(datetime,getdate()) - 0.5)
    243. and Comments like '%fail%'
    244. and Comments like '%error%'
    245. and processinfo not in ('Server','Logon')
    246. if(@errorlogcount >= 1)
    247. begin
    248. select date_time as Date,processinfo as ProcessInfo, Comments from
    249. where date_time > (CONVERT(datetime,getdate()) - 0.5)
    250. and Comments like '%fail%'
    251. and Comments like '%error%'
    252. and processinfo not in ('Server','Logon')
    253. end
    254. else
    255. begin
    256. select 'Error Log' as Date, 'check did not find out anything major'
    257. as ProcessInfo, 'but will still advise to please verify manually' as Comments
    258. end
    259. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    260. $command6 = New-Object System.Data.OleDb.OleDbCommand $SQLServerErrorlog,$connection
    261. $connection.Open()
    262. ##Get the results of our command into a DataSet object, and close the connection
    263. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command6
    264. $dataSet6 = New-Object System.Data.DataSet
    265. $dataAdapter.Fill($dataSet6)
    266. $connection.Close()
    267. $frag6 = $dataSet6.Tables | Select-Object -Expand Rows|select
    268. -Property Date,processinfo,Comments | ConvertTo-HTML -AS Table -Fragment
    269. -PreContent '<h2>SQLServer ErroLog Information</h2>'|Out-String
    270. $colorTagTable.Keys | foreach { $frag6 = $frag6 -replace ">$_<",($colorTagTable.$_) }
    271. write-host $frag6
    272. ##**************************************
    273. ##CPU information
    274. ##**************************************
    275. $SQLServerCPUInformation = "declare @query2008r2_cpu nvarchar(max)
    276. declare @query2012_cpu nvarchar(max)
    277. set @query2008r2_cpu = 'SELECT cpu_count AS Logical_CPU_Count,
    278. hyperthread_ratio AS Hyperthread_Ratio,
    279. cpu_count/hyperthread_ratio AS Physical_CPU_Count,
    280. physical_memory_in_bytes/1024/1024 AS Physical_Memory_in_MB
    281. FROM sys.dm_os_sys_info'
    282. set @query2012_cpu = 'SELECT cpu_count AS Logical_CPU_Count,
    283. hyperthread_ratio AS Hyperthread_Ratio,
    284. cpu_count/hyperthread_ratio AS Physical_CPU_Count,
    285. physical_memory_kb/1024/1024 AS Physical_Memory_in_MB
    286. FROM sys.dm_os_sys_info'
    287. /*SQL Object Memory Allocation*/
    288. declare @version nvarchar(128)
    289. select @version = cast(SERVERPROPERTY('Productversion') as nvarchar(128))
    290. if (@version like '11%')
    291. begin
    292. EXECUTE sp_executesql @query2012_cpu
    293. end
    294. else
    295. begin
    296. EXECUTE sp_executesql @query2008r2_cpu
    297. end
    298. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    299. $command7 = New-Object System.Data.OleDb.OleDbCommand $SQLServerCPUInformation,$connection
    300. $connection.Open()
    301. ##Get the results of our command into a DataSet object, and close the connection
    302. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command7
    303. $dataSet7 = New-Object System.Data.DataSet
    304. $dataAdapter.Fill($dataSet7)
    305. $connection.Close()
    306. $frag7 = $dataSet7.Tables | Select-Object -Expand Rows|select
    307. -Property Logical_CPU_Count,Hyperthread_Ratio,Physical_CPU_Count,
    308. Physical_Memory_in_MB | ConvertTo-HTML -AS Table -Fragment
    309. -PreContent '<h2>CPU Information</h2>'|Out-String
    310. write-host $frag7
    311. ##**************************************
    312. ##SQL Server Memory Infomration
    313. ##**************************************
    314. ## 1. Memory Allocated to SQL Server
    315. $SQLServerMemoryAllocated = "SELECT --object_name,
    316. counter_name as Counter, cntr_value/1024 as MemoryLimitSet_inMB
    317. FROM sys.dm_os_performance_counters
    318. WHERE counter_name IN ('Total Server Memory (KB)', 'Target Server Memory (KB)');"
    319. $connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    320. $command8 = New-Object System.Data.OleDb.OleDbCommand $SQLServerMemoryAllocated,$connection
    321. $connection.Open()
    322. ##Get the results of our command into a DataSet object, and close the connection
    323. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command8
    324. $dataSet8 = New-Object System.Data.DataSet
    325. $dataAdapter.Fill($dataSet8)
    326. $connection.Close()
    327. $frag8 = $dataSet8.Tables | Select-Object -Expand Rows|select
    328. -Property Counter,MemoryLimitSet_inMB | ConvertTo-HTML -AS Table
    329. -Fragment -PreContent '<h2>Memory Allocated to SQL Server</h2>'|Out-String
    330. write-host $frag8
    331. #2. Top 10 Memory Consuing Objects
    332. $SqlServerMemortConsumingobjects = "declare @query2008r2_and_less nvarchar(max)
    333. declare @query2012_and_more nvarchar(max)
    334. set @query2008r2_and_less = 'select top 10 type as Object,
    335. SUM(single_pages_kb+multi_pages_kb+virtual_memory_committed_kb+awe_allocated_kb)/1024 as Space_used_inMB
    336. from sys.dm_os_memory_clerks
    337. group by type
    338. order by 2 desc'
    339. set @query2012_and_more = 'select top 10 type as Object,
    340. SUM(pages_kb+virtual_memory_committed_kb+awe_allocated_kb)/1024 as Space_used_inMB
    341. from sys.dm_os_memory_clerks
    342. group by type
    343. order by 2 desc'
    344. /*SQL Object Memory Allocation*/
    345. declare @version nvarchar(128)
    346. select @version = cast(SERVERPROPERTY('Productversion') as nvarchar(128))
    347. if (@version like '11%')
    348. begin
    349. EXECUTE sp_executesql @query2012_and_more
    350. end
    351. else
    352. begin
    353. EXECUTE sp_executesql @query2008r2_and_less
    354. end
    355. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    356. $command9 = New-Object System.Data.OleDb.OleDbCommand $SqlServerMemortConsumingobjects,$connection
    357. $connection.Open()
    358. ##Get the results of our command into a DataSet object, and close the connection
    359. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command9
    360. $dataSet9 = New-Object System.Data.DataSet
    361. $dataAdapter.Fill($dataSet9)
    362. $connection.Close()
    363. $frag9 = $dataSet9.Tables | Select-Object -Expand Rows | select
    364. -Property Object,Space_used_inMB | ConvertTo-HTML -AS Table
    365. -Fragment -PreContent '<h2>Top 10 Memory Consuming SQL Objects</h2>'|Out-String
    366. write-host $frag9
    367. #3.
    368. $sqlservermemorypressuredetection = "declare @totalmemoryused bigint
    369. declare @bufferpool_allocated bigint
    370. declare @query2008r2_total nvarchar(max)
    371. declare @query2012_total nvarchar(max)
    372. declare @version nvarchar(128)
    373. Set @query2008r2_total = 'select SUM
    374. (single_pages_kb+multi_pages_kb+virtual_memory_committed_kb+awe_allocated_kb)/1024
    375. from sys.dm_os_memory_clerks'
    376. set @query2012_total = 'select SUM(pages_kb+virtual_memory_committed_kb+awe_allocated_kb)/1024
    377. from sys.dm_os_memory_clerks'
    378. select @version = cast(SERVERPROPERTY('Productversion') as nvarchar(128))
    379. --select @version
    380. if (@version like '11%')
    381. begin
    382. create table
    383. insert into
    384. select @totalmemoryused = value from
    385. drop table
    386. end
    387. else
    388. begin
    389. create table
    390. insert into
    391. select @totalmemoryused = value from
    392. drop table
    393. end
    394. --select @totalmemoryused
    395. select @bufferpool_allocated = cntr_value/1024
    396. FROM sys.dm_os_performance_counters
    397. WHERE counter_name IN ('Target Server Memory (KB)')
    398. if (@bufferpool_allocated > @totalmemoryused)
    399. begin
    400. Select 'Server has no Memory Issue' as Comments
    401. end
    402. else
    403. begin
    404. select 'Server Might Have Memory Issue' as Comments
    405. end
    406. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    407. $command10 = New-Object System.Data.OleDb.OleDbCommand $sqlservermemorypressuredetection,$connection
    408. $connection.Open()
    409. ##Get the results of our command into a DataSet object, and close the connection
    410. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command10
    411. $dataSet10 = New-Object System.Data.DataSet
    412. $dataAdapter.Fill($dataSet10)
    413. $connection.Close()
    414. $frag10 = $dataSet10.Tables | Select-Object -Expand Rows |select
    415. -Property Comments | ConvertTo-HTML -AS Table -Fragment
    416. -PreContent '<h2>Server Have Memory Pressure or Not</h2>'|Out-String
    417. $colorTagTable.Keys | foreach { $frag10 = $frag10 -replace ">$_<",($colorTagTable.$_) }
    418. write-host $frag10
    419. ##**************************************
    420. ##Top 10 Long Running Queries
    421. ##**************************************
    422. $LongRunningQueries = "
    423. SELECT TOP 10 DB_NAME(qt.dbid) AS DBName,
    424. o.name AS ObjectName,
    425. qs.total_worker_time / 1000000 / qs.execution_count As Avg_MultiCore_CPU_time_sec,
    426. qs.total_worker_time / 1000000 as Total_MultiCore_CPU_time_sec,
    427. qs.total_elapsed_time / qs.execution_count / 1000000.0 AS Average_Seconds,
    428. qs.total_elapsed_time / 1000000.0 AS Total_Seconds,
    429. qs.execution_count as Count,
    430. qs.last_execution_time as Time,
    431. SUBSTRING (qt.text,qs.statement_start_offset/2,
    432. (CASE WHEN qs.statement_end_offset = -1
    433. THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
    434. ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS Query
    435. --,qt.text
    436. --,qp.query_plan
    437. FROM sys.dm_exec_query_stats qs
    438. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
    439. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
    440. LEFT OUTER JOIN sys.objects o ON qt.objectid = o.object_id
    441. where last_execution_time > getdate()-1
    442. ORDER BY average_seconds DESC
    443. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    444. $command11 = New-Object System.Data.OleDb.OleDbCommand $LongRunningQueries,$connection
    445. $connection.Open()
    446. ##Get the results of our command into a DataSet object, and close the connection
    447. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command11
    448. $dataSet11 = New-Object System.Data.DataSet
    449. $dataAdapter.Fill($dataSet11)
    450. $connection.Close()
    451. $frag11 = $dataSet11.Tables | Select-Object -Expand Rows|select
    452. -Property DBName,ObjectName,Avg_MultiCore_CPU_time_sec,
    453. Total_MultiCore_CPU_time_sec,Average_Seconds,Total_Seconds,Count,
    454. Time,Query| ConvertTo-HTML -AS Table -Fragment
    455. -PreContent '<h2>Top 10 Long Running Query</h2>'|Out-String
    456. write-host $frag11
    457. ##**************************************
    458. ##Top 10 CPU Consuming Query
    459. ##**************************************
    460. $CPUConsumingQuery = "
    461. SELECT TOP 10 DB_NAME(qt.dbid) as DBName,
    462. o.name AS ObjectName,
    463. qs.total_worker_time / 1000000 / qs.execution_count AS Avg_MultiCore_CPU_time_sec,
    464. qs.total_worker_time / 1000000 As Total_MultiCore_CPU_time_sec,
    465. qs.total_elapsed_time / 1000000 / qs.execution_count As Average_Seconds,
    466. qs.total_elapsed_time / 1000000 As Total_Seconds,
    467. (total_logical_reads + total_logical_writes) / qs.execution_count as Average_IO,
    468. total_logical_reads + total_logical_writes as Total_IO,
    469. qs.execution_count as Count,
    470. qs.last_execution_time as Time,
    471. SUBSTRING(qt.[text], (qs.statement_start_offset / 2) + 1,
    472. (
    473. (
    474. CASE qs.statement_end_offset
    475. WHEN -1 THEN DATALENGTH(qt.[text])
    476. ELSE qs.statement_end_offset
    477. END - qs.statement_start_offset
    478. ) / 2
    479. ) + 1
    480. ) as Query
    481. --,qt.text
    482. --,qp.query_plan
    483. FROM sys.dm_exec_query_stats AS qs
    484. CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
    485. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
    486. LEFT OUTER JOIN sys.objects o ON qt.objectid = o.object_id
    487. where qs.execution_count > 5 --more than 5 occurrences
    488. ORDER BY Total_MultiCore_CPU_time_sec DESC
    489. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    490. $command12 = New-Object System.Data.OleDb.OleDbCommand $CPUConsumingQuery,$connection
    491. $connection.Open()
    492. ##Get the results of our command into a DataSet object, and close the connection
    493. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command12
    494. $dataSet12 = New-Object System.Data.DataSet
    495. $dataAdapter.Fill($dataSet12)
    496. $connection.Close()
    497. $frag12 = $dataSet12.Tables | Select-Object -Expand Rows |select
    498. -Property DBName,ObjectName,Avg_MultiCore_CPU_time_sec,
    499. Total_MultiCore_CPU_time_sec,Average_Seconds,Total_Seconds,Average_IO,
    500. Total_IO,Count,Time,Query | ConvertTo-HTML -AS Table -Fragment
    501. -PreContent '<h2>Top 10 CPU Consuming Query</h2>'|Out-String
    502. write-host $frag12
    503. ##**************************************
    504. ##Top 10 IO Consuming Query
    505. ##**************************************
    506. $IOConsumingQuery = "
    507. SELECT TOP 10 DB_NAME(qt.dbid) AS DBName,
    508. o.name AS ObjectName,
    509. qs.total_elapsed_time / 1000000 / qs.execution_count As Average_Seconds,
    510. qs.total_elapsed_time / 1000000 As Total_Seconds,
    511. (total_logical_reads + total_logical_writes ) / qs.execution_count AS Average_IO,
    512. (total_logical_reads + total_logical_writes ) AS Total_IO,
    513. qs.execution_count AS Count,
    514. last_execution_time As Time,
    515. SUBSTRING (qt.text,qs.statement_start_offset/2,
    516. (CASE WHEN qs.statement_end_offset = -1
    517. THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
    518. ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS Query
    519. --,qt.text
    520. --,qp.query_plan
    521. FROM sys.dm_exec_query_stats qs
    522. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
    523. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
    524. LEFT OUTER JOIN sys.objects o ON qt.objectid = o.object_id
    525. where last_execution_time > getdate()-1
    526. ORDER BY average_IO DESC
    527. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    528. $command13 = New-Object System.Data.OleDb.OleDbCommand $IOConsumingQuery,$connection
    529. $connection.Open()
    530. ##Get the results of our command into a DataSet object, and close the connection
    531. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command13
    532. $dataSet13 = New-Object System.Data.DataSet
    533. $dataAdapter.Fill($dataSet13)
    534. $connection.Close()
    535. $frag13 = $dataSet13.Tables | Select-Object -Expand Rows |Select
    536. -Property DBName,ObjectName,Average_Seconds,
    537. Total_Seconds, Average_IO, Total_IO, Count, Time, Query | ConvertTo-HTML
    538. -AS Table -Fragment -PreContent '
    539. <h2>Top 10 IO Consuming Query</h2>'|Out-String
    540. write-host $frag13
    541. ##**************************************
    542. ##CPU Pressure
    543. ##**************************************
    544. $CPUPressure = "
    545. SELECT CAST(100.0 * SUM(signal_wait_time_ms) /
    546. SUM (wait_time_ms) AS NUMERIC(20,2)) AS Pct_Signal_CPU_Waits,
    547. 'if Perc_signal_cpu_waits is > 15%, it means we have CPU pressure' as Comment,
    548. CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) /
    549. SUM (wait_time_ms) AS NUMERIC(20,2)) AS Pct_Resource_Waits
    550. FROM sys.dm_os_wait_stats
    551. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    552. $command14 = New-Object System.Data.OleDb.OleDbCommand $CPUPressure,$connection
    553. $connection.Open()
    554. ##Get the results of our command into a DataSet object, and close the connection
    555. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command14
    556. $dataSet14 = New-Object System.Data.DataSet
    557. $dataAdapter.Fill($dataSet14)
    558. $connection.Close()
    559. $frag14 = $dataSet14.Tables | Select-Object -Expand Rows | select -Property Pct_Signal_CPU_Waits,Comment,
    560. Pct_Resource_Waits | ConvertTo-HTML -AS Table -Fragment
    561. -PreContent '<h2>CPU Pressure Detection</h2>'|Out-String
    562. write-host $frag14
    563. ##**************************************
    564. ##Wait Type % Calc
    565. ##**************************************
    566. $WaitTimePercentage = "declare @totalwait_time_ms float
    567. select @totalwait_time_ms = sum(wait_time_ms)
    568. FROM sys.dm_os_wait_stats
    569. where wait_time_ms > 0
    570. select top 10 wait_type as WaitEvent,
    571. wait_time_ms/1000 as Time_inSec,
    572. round(100*(cast(wait_time_ms as float)/@totalwait_time_ms),2) as PctUsed
    573. FROM sys.dm_os_wait_stats
    574. where wait_time_ms > 0
    575. order by wait_time_ms desc
    576. "$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
    577. $command15 = New-Object System.Data.OleDb.OleDbCommand $WaitTimePercentage,$connection
    578. $connection.Open()
    579. ##Get the results of our command into a DataSet object, and close the connection
    580. $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command15
    581. $dataSet15 = New-Object System.Data.DataSet
    582. $dataAdapter.Fill($dataSet15)
    583. $connection.Close()
    584. $frag15 = $dataSet15.Tables | Select-Object -Expand Rows |select
    585. -Property WaitEvent,Time_inSec,PctUsed | ConvertTo-HTML -AS Table
    586. -Fragment -PreContent '<h2>Wait Type % Allocation on Server</h2>'|Out-String
    587. write-host $frag15
    588. ##**************************************
    589. ##Final Code to Combine all fragments
    590. ##**************************************
    591. ConvertTo-HTML -head $a -PostContent $frag1,$frag2,$frag3,$frag4,$frag5,
    592. $frag6,$frag7,$frag8,$frag9,$frag10,$frag14,$frag15,$frag11,$frag12,$frag13
    593. -PreContent "<h1>SQL Server Heatlh Check Report</h1>" | Out-File $OutputFile_new
    594. $smtpServer = "mx.XYZ.com"
    595. $anonUsername = "anonymous"
    596. $anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
    597. $anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)
    598. $attachment = "$OutputFile_new"
    599. $body= Get-Content $OutputFile_new
    600. #write-host $body
    601. $subject = "Health Check Report for Server: " + $servername
    602. write-host "Sending email"
    603. Send-MailMessage -to "abc@xyz.com" -from "DoNotReply@xyz.com"
    604. -SmtpServer "mx.xyz.com" -subject $subject -credential $anonCredentials
    605. -BodyAsHtml "$body" #-Attachments $attachment #$OutputFile_new
    606. $Stoptime = Get-Date
    607. Write-host $Stoptime
    608. }remove-variable starttime
    609. remove-variable servernames
    610. remove-variable servername
    611. remove-variable dataSource
    612. remove-variable database
    613. remove-variable TableHeader
    614. remove-variable path
    615. remove-variable name
    616. remove-variable OutputFile_new
    617. remove-variable a
    618. remove-variable colorTagTable
    619. remove-variable connectionDetails
    620. remove-variable connection
    621. remove-variable dataAdapter
    622. remove-variable sql_server_info
    623. remove-variable sqlserverAgent
    624. remove-variable SQLServerDatabaseState
    625. remove-variable SQLJob
    626. remove-variable SQLServerDatabaseBackup
    627. remove-variable SQLServerErrorlog
    628. remove-variable SQLServerCPUInformation
    629. remove-variable SQLServerMemoryAllocated
    630. remove-variable SqlServerMemortConsumingobjects
    631. remove-variable sqlservermemorypressuredetection
    632. remove-variable LongRunningQueries
    633. remove-variable CPUConsumingQuery
    634. remove-variable IOConsumingQuery
    635. remove-variable CPUPressure
    636. remove-variable WaitTimePercentage
    637. remove-variable smtpServer
    638. remove-variable anonUsername
    639. remove-variable anonPassword
    640. remove-variable anonCredentials
    641. remove-variable attachment
    642. remove-variable body
    643. remove-variable subject
    644. remove-variable Stoptime
    645. remove-variable dataSet1
    646. remove-variable dataSet2
    647. remove-variable dataSet3
    648. remove-variable dataSet4
    649. remove-variable dataSet5
    650. remove-variable dataSet6
    651. remove-variable dataSet7
    652. remove-variable dataSet8
    653. remove-variable dataSet9
    654. remove-variable dataSet10
    655. remove-variable dataSet11
    656. remove-variable dataSet12
    657. remove-variable dataSet13
    658. remove-variable dataSet14
    659. remove-variable dataSet15
    660. remove-variable command1
    661. remove-variable command2
    662. remove-variable command3
    663. remove-variable command4
    664. remove-variable command5
    665. remove-variable command6
    666. remove-variable command7
    667. remove-variable command8
    668. remove-variable command9
    669. remove-variable command10
    670. remove-variable command11
    671. remove-variable command12
    672. remove-variable command13
    673. remove-variable command14
    674. remove-variable command15
    675. remove-variable frag1
    676. remove-variable frag2
    677. remove-variable frag3
    678. remove-variable frag4
    679. remove-variable frag5
    680. remove-variable frag6
    681. remove-variable frag7
    682. remove-variable frag8
    683. remove-variable frag9
    684. remove-variable frag10
    685. remove-variable frag11
    686. remove-variable frag12
    687. remove-variable frag13
    688. remove-variable frag14
    689. remove-variable frag15
    690. ##Powershell Code Ends##
    复制代码



    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    运维联盟俱乐部 ( 冀ICP备19036648号 )

    GMT+8, 2024-4-29 22:31 , Processed in 0.052951 second(s), 21 queries , Gzip On.

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表