本文介紹如何用PowerShell腳本實現SQL Server數據庫容量監控
創新互聯建站是一家專注于成都網站建設、網站設計與策劃設計,大方網站建設哪家好?創新互聯建站做網站,專注于網站建設十多年,網設計領域的專業建站公司;建站業務涵蓋:大方等地區。大方做網站價格咨詢:18980820575
閑話就不多說,直入主題
一、建表
為每臺服務器創建一個表,用于記錄服務器各個數據庫的容量,以服務器名作為表名。
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
}
}
}效果圖:

網頁標題:PowerShell:30行代碼輕松實現SQLServer數據庫容量監控
網頁地址:http://www.yijiale78.com/article8/pcppop.html
成都網站建設公司_創新互聯,為您提供微信小程序、面包屑導航、網站策劃、ChatGPT、標簽優化、網站營銷
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯