Skip to content

October 20, 2011

Powershell Script to check for low drive space

by Scott Newman

Just what it says.  This will email you when your drive space gets below the desired threshold.


function sendMail($srv, $DriveName, $free) {
	$subject = "Low Drive Space on $srv"
	$body = "<p style='font-family: calibri;'>The <B>$DriveName</B> on server <B>$srv</B> has only <B>$free % </B> free.<BR/>
	Please try to free up some space so it is above $percentThreshold% free space.
	</p>"
	
	# Init Mail address objects
	$emailFrom = New-Object system.net.Mail.MailAddress "donotreply@yourcomany.com" , "Low Drive Space on $srv"
	$emailTo = New-Object system.net.Mail.MailAddress $alertEmail , "Low Drive Space"
	$smtp = new-object Net.Mail.SmtpClient($mailServer)
	$MailMessage = new-object Net.Mail.MailMessage($emailFrom, $emailTo, $subject, $body)
	$MailMessage.IsBodyHtml = $true
	
	$smtp.Send($MailMessage)
}

function CheckDriveSpace($servername)
{
	$drives = gwmi win32_logicaldisk -filter "drivetype=3" -ComputerName ($servername) -ErrorAction SilentlyContinue
	foreach($drive in $drives)
	{
		$PercentFree = [int]([Int64]$drive.FreeSpace / [Int64]($drive.Size) * 100) 
		
		#SaveDriveinfo $ServerName $Drive.DeviceID $Drive.FreeSpace $drive.Size $PercentFree
		
		if($PercentFree -lt $percentThreshold)
		{	
			sendMail $servername $drive.DeviceID $PercentFree
		}
	}
}

function Main()
{
	try
	{
		$servers = Get-Content("C:\Servers.txt")
		foreach($server in $servers)
		{
			CheckDriveSpace $server
		}
		return 0;
	}
	catch
	{
		# Handle the error
		$err = $_.Exception
		write-host $err.Message
		while( $err.InnerException ) 
		{
			$err = $err.InnerException
			write-output $err.Message
		}
		return 1;
	}
}


Clear-Host
$percentThreshold = 15
$alertEmail = "dba@yourcompany.com"
$mailServer = "mail.yourcompany.com"
Main

Read more from Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: