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.
	# Init Mail address objects
	$emailFrom = New-Object "" , "Low Drive Space on $srv"
	$emailTo = New-Object $alertEmail , "Low Drive Space"
	$smtp = new-object Net.Mail.SmtpClient($mailServer)
	$MailMessage = new-object Net.Mail.MailMessage($emailFrom, $emailTo, $subject, $body)
	$MailMessage.IsBodyHtml = $true

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()
		$servers = Get-Content("C:\Servers.txt")
		foreach($server in $servers)
			CheckDriveSpace $server
		return 0;
		# Handle the error
		$err = $_.Exception
		write-host $err.Message
		while( $err.InnerException ) 
			$err = $err.InnerException
			write-output $err.Message
		return 1;

$percentThreshold = 15
$alertEmail = ""
$mailServer = ""

Read more from Powershell

Leave a Reply

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

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: