Powershell script to send disk space alerts for a list of servers

 I created a windows task scheduler job and let it run daily to check disk free space on all 200+ database servers I managed and sent email alerts when free space is lower than given criteria.

(btw, I have a nightly job to collecting all free space and save in a database, will blog that later)

first export the list of server names to c:\sql\diskspaceServerList.txt

then copy below to a file named diskspace1.ps1

then create windows task scheduler job and run this script at the time you specified.


$text=Get-Content 'c:\sql\diskspaceServerList.txt'

$receipients='dba@transformsso.ca' <#,'Husam.Ibrahim@transformsso.ca','servicedesk@transformsso.ca'#>


$lowPercent="20"

$TotalComputers=$text.Length

write-host "the total number of computers is $TotalComputers"

$body=""

For ($i=0; $i -lt $text.Length; $i++) {

    $computername= $text[$i].ToString()

    Write-Host "current check computer $computername";

    if ( ([string]::IsNullOrEmpty($computername)))       { continue }

    $GetFreespace= Get-WmiObject -Class win32_volume -ComputerName $computername | Select-Object Name,Label,@{N='free';E={[math]::round($_.freespace / 1GB,2)}}, @{N='capacity';E={[math]::Round($_.capacity / 1GB,2)}}

    foreach($dspace in $GetFreespace) {

        if (($dspace.capacity -gt 0) -and ($dspace.name -match ":")) {

        if($dspace.free * 100 / ($dspace.capacity) -lt $lowPercent) {

                $percent= $dspace.free / ($dspace.capacity)

        $diskspace="<span style='color:red'>"+ $dspace.name + "</span> " + $dspace.label + " free space is <span style='color:red'>" + $dspace.free + "</span>GB out of " +$dspace.capacity + "GB free percent: <span style='color:red'>" + ($percent).ToString(“P”)+"</span>"

                $body= $body + "`n <span style='color:red'> $computername </span> disk space daily check " + $diskspace + "`n</br>"

          }

        }

    }

}

               $subject="  disk space less than $lowPercent%   " 

                Send-MailMessage -From 'dba@transformsso.ca' -To $receipients -Subject $subject -Body $body  -DeliveryNotificationOption OnSuccess, OnFailure -BodyAsHtml -SmtpServer 'smtp.transformsso.ca'


Comments

Popular posts from this blog

Sysaux tablespace is too big

SQL server agent password change, not require reboot, but requires retype AD user when reboot in the future

GENERATE RSA KEYS WITH SSH BY USING PUTTYGEN