您好,登錄后才能下訂單哦!
本文介紹如何用PowerShell腳本實現SQL Server數據庫容量監控
閑話就不多說,直入主題
一、建表
為每臺服務器創建一個表,用于記錄服務器各個數據庫的容量,以服務器名作為表名。
CREATE TABLE table_name( [LOG_DATE] [varchar](20) NULL, [DB_NAME] [varchar](50) NULL, [TOTAL_SIZE_MB] [numeric](15, 2) NULL, [USE_SIZE_MB] [numeric](15, 2) NULL, [FREE_SIZE_MB] [numeric](15, 2) NULL, [DAILY_GROWTH_MB] [numeric](15, 2) NULL DEFAULT ((0)) )
二、數據收集
要點:
1. 主要利用sp_msforeachdb、sp_spaceused循環獲取各數據庫容量數據,簡化代碼
2. today_use_size = total_szie - free_size
3. growth_szie = today_use_size - yesterday_use_size
4. chkservers.txt存放服務器名
5. 創建作業,每天定時執行(如需調整為每周、月執行,修改$yesterday=$today.adddays(-1)及作業頻率即可)
$MonitorServer='' $servers=gc F:\DBA\chkservers.txt $today=Get-Date $log_date=$today.toString('yyyyMMdd') $yesterday=$today.adddays(-1) $compare_date=$yesterday.toString('yyyyMMdd') Foreach($server in $servers){ if($server.length -gt 0){ $results=invoke-sqlcmd "exec sp_msforeachdb 'if(db_id(''?'') not in(1,2,3,4)) begin exec [?]..sp_spaceused end'" -ServerInstance $server For($n=0;$n -lt $results.length;$n=$n+2){ $db_name=$results[$n].database_name $db_total_size=$results[$n].database_size $db_free_size=$results[$n].'unallocated space' $total_size=$db_total_size.substring(0,$db_total_size.length-3) $free_size=$db_free_size.substring(0,$db_free_size.length-3) $today_use_size=$total_size-$free_size $count=invoke-sqlcmd "select count(1) as count from DBMonitor..$server where LOG_DATE='$compare_date' and DB_NAME='$db_name'" -ServerInstance $MonitorServer if($count.count -gt 0){ $comp_results=invoke-sqlcmd "select MAX(USE_SIZE_MB) as USE_SIZE_MB from DBMonitor..$server where LOG_DATE='$compare_date' and DB_NAME='$db_name'" -ServerInstance $MonitorServer $yesterday_use_size=$comp_results.USE_SIZE_MB $growth_size=$today_use_size-$yesterday_use_size } else{ $growth_size=0 } invoke-sqlcmd "insert into DBMonitor..$server select '$log_date','$db_name',$total_size,$today_use_size,$free_size,$growth_size" -ServerInstance $MonitorServer } } }
效果圖:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。