● Windows - Low Disk Space Warning Email Alert

posted 1 Jan 2017, 16:09 by Dominique Cressatti   [ updated 22 Mar 2017, 14:26 ]

Quick Perl script to send you an email alert when your Windows server's system drive free space goes down 100 Meg (or below), so you can take action before the server completely runs out of space and thus stops functioning.

What you need to have and do:
  • Active Perl on your server
  • Win32::DriveInfo and Net::SMTP Perl modules
  • Set the $recipient variable as the recipient who will receive the email alert
  • Set the $from variable as the email address of sender of this email
  • Set the $host variable as the name of the server to be monitored
  • Set the $mailserver variable as the FQN of your local mail server
  • Schedule to run this script using either with Windows AT or better the Windows scheduler

use Win32::DriveInfo; 
use Net::SMTP;

$recipient = 'someone@yourdomain.com'; # The recipient of this email alert
$from = 'administrator@yourdomain.com' # The "from" part this email alert
$host = `hostname`;
$mailserver = 'FQN_of_your_local_mail_server'
$SystemDrive = $ENV{"SYSTEMDRIVE"}, "\n";
$TotalNumberOfFreeBytes = Win32::DriveInfo::DriveSpace($SystemDrive);
$TotalOfFreeMegs = $TotalNumberOfFreeBytes / 1048576;
$TotalOfFreeMegs = &round ($TotalOfFreeMegs);


if ($TotalNumberOfFreeBytes < 104857600) # check to see if free space < 100 Megs
{

    $smtp = Net::SMTP->new($mailserver); 
    $smtp->mail($from); # The "from" part this email alert
    $smtp->to($recipient\); # The recipient of this email alert
    $smtp->data();
    $smtp->datasend("to:$recipient\n"); # What's get written after "To" part in the email
    $smtp->datasend("Subject: Warning: Low space on $host root drive\n"); # subject of the email
    $smtp->datasend("\n");

    # body of the email from now on
    $smtp->datasend("The free space left on $host is: $TotalOfFreeMegs Megs !\n\n");
    $smtp->dataend();
    $smtp->quit;
    

sub round {
    my($number) = shift;
    return int($number + .5);
}