SQL Server Tips

Using PowerShell To Monitor Disk Usage

Updated
6 min read
Written by
Mark Varnas

Part of the database and system administrator’s daily routine consists of monitoring disk usage.

It can be achieved manually, however, it is much more logical to do this automatically.

Even better – the automatic script can warn only when a specific space threshold on the specific drive has left.

In this article, we are going to share a free disk usage alert and explain how to use it, and how it works internally.

All you need to get it done is access to monitored servers and PowerShell (PS).

Prerequisites

Two important things before we begin:

  • By default, the current account that will run the script must be a member of the Administrators group on the remote computer;
  • The execution policy on PowerShell should be set to RemoteSigned.

To check that and change if needed, these steps should be followed:

  1. Open Powershell as an Administrator. To do this, click on the Start button and type “PowerShell”.
  2. Then right-click the mouse on Windows PowerShell ISE (simple Windows PowerShell will also work in this step), and choose Run as administrator as it is shown in Figure 1.
  1. When the window opens, enter Get-ExecutionPolicy and hit enter. If it is not Unrestricted or RemoteSigned, enter Set-ExecutionPolicy RemoteSigned. You will be asked if you are sure.
  2. Enter Y and hit Enter.

Now Powershell is ready to run the monitoring script. Let’s analyze that.

Script settings

  1. To begin with look at the top part of the script settings and find the path to settings.csv
$fromemail = 'SomeEmailUsedForMonitoring@ YourCompany.com'
$recipients = 'DestinationEmailAddress@ YourCompany.com' #several recipients may be separated by comma
$mailserver = 'YourCoolMailServerName.YourCompany.com'

$csv = Import-Csv 'E:\Scripts\Settings.csv' ### Read settings from file

$HTMLCollection = "<font color=""black"" face=""Arial, Verdana"" size=""3"">
Hi there, <br> This report was sent because drives listed below have less than defined percentage of free space left. <br><br>"


    foreach ( $args in $csv ) {

$DriveLetter = $args.Drive

$Collection = get-WmiObject win32_logicaldisk -ComputerName $args.ComputerName  -Filter "DeviceID='$DriveLetter'"  |

select SystemName,DeviceID,VolumeName,@{Label="TotalSize";Expression={$_.Size / 1gb -as [int] }},@{Label="FreeSize";Expression={$_.freespace / 1gb -as [int] }},@{Label="FreePercent";Expression={$_.freespace/$_.Size*100 }}   

If ($Collection.FreePercent -lt $args.Threshold) {

$HTMLCollection += ('Drive <b>' + $Collection.DeviceID + '</b> on host <b>' + $args.ComputerName + '</b> has less than <b>' + $args.Threshold + '% </b> threshold of free space. <br>'  ) 

}
}

Send-MailMessage -From $fromemail -To $recipients -Subject "Disk Space Usage Report" -SmtpServer $mailserver -BodyAsHTML -Body $HTMLCollection -priority High
  1. Now open the Settings.csv file, using your favorite text editor (Notepad works fine).
  2. Do not edit the first row (header), just add new rows (or edit existing ones) below that contain the Computer Name, Drive, and Drive capacity threshold.
    You can add as many servers and drives as you need just separate all values by a comma.

Here is an example:
ComputerName,Drive,Threshold
server1,E:,10
server1,F:,15
server2,E:,12

  1. Nothing else should be changed inside the script. It will automatically iterate the settings list, generate HTML text, and send it via email to the recipients’ list. An example of email message content is in Figure 4 below.

Scheduling script to run automatically

The next step would be to schedule this script so it can run automatically. This can be done at least in two ways:

  • Using Task Scheduler
  • Using Microsoft SQL Server Agent jobs (this requires SQL Server version, higher than Express edition, installed)

In this article, we will describe the first option.

  1. First, open Start, type “Task Scheduler,” and hit Enter, as shown in Figure 5.
  1. When the Task Scheduler window opens, click the Create Task… button.
  2. On the General tab fill in Name, and Description, pick Run whether the user is logged on or not, and pick Run with highest privileges.
  3. On the Triggers tab click New, choose preferred schedule (example – Daily at 8 am), and tick the box Synchronize across time zones, click OK.
  4. Then go to the Actions tab, click New, and fill in Program/script by text powershell and Add arguments (optional) by –file E:\Scripts\DiskSpaceMonitoring.ps1 (change path where PS script is located at).
    Example screenshot in Figure 6.
  5. After those boxes are filled, click OK twice.

Before starting to use this script in production, we recommend setting high threshold values to ensure that no firewalls or spam filters block the emails and that all permissions are in place.

Enjoy using the disk usage monitoring alert!

Speak with a SQL Expert

In just 30 minutes, we will show you how we can eliminate your SQL Server headaches and provide 
operational peace of mind

Article by
Mark Varnas
Founder | CEO | SQL Veteran
Hey, I'm Mark, one of the guys behind Red9. I make a living performance tuning SQL Servers and making them more stable.

Discover More

SQL Server Health Check SQL Server Migrations & Upgrades SQL Server Performance Tuning SQL Server Security SQL Server Tips

Discover what clients are saying about Red9

Red9 has incredible expertise both in SQL migration and performance tuning.

The biggest benefit has been performance gains and tuning associated with migrating to AWS and a newer version of SQL Server with Always On clustering. Red9 was integral to this process. The deep knowledge of MSSQL and combined experience of Red9 have been a huge asset during a difficult migration. Red9 found inefficient indexes and performance bottlenecks that improved latency by over 400%.

Rich Staats 5 stars
Rich Staats
Cloud Engineer
MetalToad

Always willing to go an extra mile

Working with Red9 DBAs has been a pleasure. They are great team players and have an expert knowledge of SQL Server database administration. And are always willing to go the extra mile to get the project done.
5 stars
Evelyn A.
Sr. Database Administrator

Boosts server health and efficiency for enhanced customer satisfaction

Since adding Red9 to the reporting and DataWarehousing team, Red9 has done a good job coming up to speed on our environments and helping ensure we continue to meet our customer's needs. Red9 has taken ownership of our servers ensuring they remain healthy by monitoring and tuning inefficient queries.
5 stars
Andrew F.
Datawarehousing Manager
See more testimonials