Thursday, January 28, 2016

Low Disk Space Email Notification

# Set Global Parameters
$emailTO = "SomeOne@SomeDomain.com"
$emailFrom = "SomeOne@SomeDomain.com"
$smtpServer = "SMTPserverInfo"

$computers = ("server1","server2","server3","server4")
$i = 0

# Get Drive Data
$report = @(
foreach($computer in $computers)
{
$drives = Get-WmiObject -ComputerName $computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
     foreach($drive in $drives)
     {
          # Calculate Free Space
          $obj = new-object psobject -Property @{
               ComputerName = $computer
               Drive = $drive.DeviceID
               Size = $drive.size / 1GB
               Free = $drive.freespace / 1GB
               PercentFree = $drive.freespace / $drive.size * 100
               }
          # Monitor for 10% or less in free space and report accordingly
          if ($obj.PercentFree -lt 10) {
               $obj | Format-Table ComputerName,Drive,@{n='Size';e={'{0:N1}' -f $_.Size}},@{n='Free';e={'{0:N1}' -f $_.Free}},@{n='PercentFree';e={'{0:N1}' -f $_.PercentFree}} | Out-String
               $i++
               }
     }
   
}
)

# Send notification if script finds more than 0 drives with less than 10% free space
if ($i -gt 0)
   {
       foreach ($user in $emailTo)
                {
        echo "Sending Email Notification to $user"
        $smtp = New-Object Net.Mail.SmtpClient($smtpServer)
        $subject = "Server with Low Disk Space"
        foreach ($line in $report)
            {
                $body += "$line "
                }
        Send-MailMessage -to $user -From $emailFrom -SmtpServer $smtpServer -Subject $Subject -Body $body
                }
   }


Sorce

No comments: