Difficulty: Intermediate

This guide will teach you how to take a powershell script, turn it into a scheduled task, and have the output of the script be emailed to you. The script I’m going to be demoing here is a simple disk space check that runs on a list of servers you define. For every server in the list with a drive that has less than 20% of storage left, the drive and amount of disk space left will be shown.

Before we begin working with the script, we must first prepare our server for powershell. Windows 2008 Server may already have powershell preinstalled. If it is, you will be able to find it in START > Accessories > Windows Powershell. If it is not there, then you will have to install it by going into control panel, programs and features, and turn windows features on or off, and enabling Windows Powershell.

Disk Space Report
Source: http://gallery.technet.microsoft.com/scriptcenter/Disk-Space-Report-Reports-98e64d65

Copy the following script and paste it in notepad on your server. Save the file as a “All type” and name it diskspacereport.ps1

Save this file somewhere that you will remember where it is. For me, I saved it in a new folder I created on the Server’s C: drive. (Ex: C:\powershell\diskspacereport)

You will need to edit this file with notepad to make changes to the script.

#############################################################################
# #
# Check disk space and send an HTML report as the body of an email. #
# Reports only disks on computers that have low disk space. #
# Author: Mike Carmody #
# Some ideas extracted from Thiyagu’s Exchange DiskspaceHTMLReport module. #
# Date: 8/10/2011 #
# I have not added any error checking into this script yet. #
# #
# #
#############################################################################
# Continue even if there are errors
$ErrorActionPreference = “Continue”;

#########################################################################################
# Items to change to make it work for you.
#
# EMAIL PROPERTIES
# – the $users that this report will be sent to.
# – near the end of the script the smtpserver, From and Subject.

# REPORT PROPERTIES
# – you can edit the report path and report name of the html file that is the report.
#########################################################################################

# Set your warning and critical thresholds
$percentWarning = 15;
$percentCritcal = 10;

# EMAIL PROPERTIES
# Set the recipients of the report.
$users = “EMAILTO@COMPANY.COM”
#$users = “You@company.com” # I use this for testing by uing my email address.
#$users = “you@company.com”, “manager@company.com”, “etc@company.com”; # can be sent to individuals.

# REPORT PROPERTIES
# Path to the report
$reportPath = “\\WEBSERVER\C$\inetpub\wwwroot\WEB_DIRECTORY\index.html”;
# Report name
$reportName = “index.html”;

# Path and Report name together
$diskReport = $reportPath + $reportName

#Set colors for table cell backgrounds
$redColor = “#FF0000”
$orangeColor = “#FBB917”
$whiteColor = “#FFFFFF”

# Count if any computers have low disk space. Do not send report if less than 1.
$i = 0;

# Get computer list to check disk space
$computers = Get-Content “H:\~PROJECTS\Reports\Servers\servers.txt”;
$datetime = Get-Date -Format “MM-dd-yyyy_HHmmss”;

# Remove the report if it has already been run today so it does not append to the existing report
If (Test-Path $diskReport)
{
Remove-Item $diskReport
}

# Cleanup old files..
$Daysback = “-7”
$CurrentDate = Get-Date;
$DateToDelete = $CurrentDate.AddDays($Daysback);
Get-ChildItem $reportPath | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item;

# Create and write HTML Header of report
$titleDate = get-date -uformat “%m-%d-%Y – %A”
$header = ”
<html>
<head>
<meta http-equiv=’Content-Type’ content=’text/html; charset=iso-8859-1′>
<title>DiskSpace Report</title>
<STYLE TYPE=’text/css’>
<!–
td {
font-family: Tahoma;
font-size: 11px;
border-top: 1px solid #999999;
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
border-left: 1px solid #999999;
padding-top: 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
}
body {
margin-left: 5px;
margin-top: 5px;
margin-right: 0px;
margin-bottom: 10px;
table {
border: thin solid #000000;
}
–>
</style>
</head>
<body>
<table width=’100%’>
<tr bgcolor=’#CCCCCC’>
<td colspan=’7′ height=’25’ align=’center’>
<font face=’tahoma’ color=’#003399′ size=’4′><strong>DiskSpace Report for $titledate</strong></font>
</td>
</tr>
</table>

Add-Content $diskReport $header

# Create and write Table header for report
$tableHeader = ”
<table width=’100%’><tbody>
<tr bgcolor=#CCCCCC>
<td width=’10%’ align=’center’>Server</td>
<td width=’5%’ align=’center’>Drive</td>
<td width=’15%’ align=’center’>Drive Label</td>
<td width=’10%’ align=’center’>Total Capacity(GB)</td>
<td width=’10%’ align=’center’>Used Capacity(GB)</td>
<td width=’10%’ align=’center’>Free Space(GB)</td>
<td width=’5%’ align=’center’>Freespace %</td>
</tr>

Add-Content $diskReport $tableHeader

# Start processing disk space reports against a list of servers
foreach($computer in $computers)
{
$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter “DriveType = 3″
$computer = $computer.toupper()
foreach($disk in $disks)
{
$deviceID = $disk.DeviceID;
$volName = $disk.VolumeName;
[float]$size = $disk.Size;
[float]$freespace = $disk.FreeSpace;
$percentFree = [Math]::Round(($freespace / $size) * 100, 2);
$sizeGB = [Math]::Round($size / 1073741824, 2);
$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
$usedSpaceGB = $sizeGB – $freeSpaceGB;
$color = $whiteColor;

# Set background color to Orange if just a warning
if($percentFree -lt $percentWarning)
{
$color = $orangeColor

# Set background color to Orange if space is Critical
if($percentFree -lt $percentCritcal)
{
$color = $redColor
}

# Create table data rows
$dataRow = ”
<tr>
<td width=’10%’>$computer</td>
<td width=’5%’ align=’center’>$deviceID</td>
<td width=’15%’ >$volName</td>
<td width=’10%’ align=’center’>$sizeGB</td>
<td width=’10%’ align=’center’>$usedSpaceGB</td>
<td width=’10%’ align=’center’>$freeSpaceGB</td>
<td width=’5%’ bgcolor=`’$color`’ align=’center’>$percentFree</td>
</tr>

Add-Content $diskReport $dataRow;
Write-Host -ForegroundColor DarkYellow “$computer $deviceID percentage free space = $percentFree”;
$i++
}
}
}

# Create table at end of report showing legend of colors for the critical and warning
$tableDescription = ”
</table><br><table width=’20%’>
<tr bgcolor=’White’>
<td width=’10%’ align=’center’ bgcolor=’#FBB917′>Warning less than 15% free space</td>
<td width=’10%’ align=’center’ bgcolor=’#FF0000′>Critical less than 10% free space</td>
</tr>

Add-Content $diskReport $tableDescription
Add-Content $diskReport “</body></html>”

# Send Notification if alert $i is greater then 0
if ($i -gt 0)
{
foreach ($user in $users)
{
Write-Host “Sending Email notification to $user”

$smtpServer = “SMTP-SERVER.DOMAIN”
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg = New-Object Net.Mail.MailMessage
$msg.To.Add($user)
$msg.From = “EMAILFROM@ADDRESS.COM”
$msg.Subject = “Environment DiskSpace Report for $titledate”
$msg.IsBodyHTML = $true
$msg.Body = get-content $diskReport
$smtp.Send($msg)
$body = “Report completed.”
}
}

Now, we need to modify our script to include our email address, company name, and SMTP server information.

# EMAIL PROPERTIES
# Set the recipients of the report.
$users = “EMAILTO@COMPANY.COM
#$users = “You@company.com” # I use this for testing by uing my email address.
#$users = “you@company.com”, “manager@company.com”, “etc@company.com”; # can be sent to individuals.

This is where you choose who will receive the report in an email. You can either send it to yourself or an Active Directory Distribution Group that is tied to a shared email address.

# REPORT PROPERTIES
# Path to the report
$reportPath = “\\WEBSERVER\C$\inetpub\wwwroot\WEB_DIRECTORY\index.html“;

The report also generates an HTML page, because of that I have the report being saved directory to my web server. For your server to have this directory, you will have to enable IIS.

Follow this guide on enabling IIS on Windows Server 2008: http://learn.iis.net/page.aspx/29/installing-iis-7-and-above-on-windows-server-2008-or-windows-server-2008-r2/

Once IIS has been enabled, go into the IIS manager on your server and create a new virtual web directory and map to the folder you created in wwwroot.

# Get computer list to check disk space
$computers = Get-Content “H:\~PROJECTS\Reports\Servers\servers.txt“;
$datetime = Get-Date -Format “MM-dd-yyyy_HHmmss”;

To add servers which this report will be used to check, you can either add them manually here and separate them with commas or you can create a simple notepad text file with a list of your servers and point the $computers path to your file like I have done above. My servers in my notepad document are formatted like this:

SERVER1
SERVER2
SERVER3

Finally, we need to provide this report SMTP settings to relay an email message once the report completes.

$smtpServer = “SMTP-SERVER-HOSTNAME.DOMAIN
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg = New-Object Net.Mail.MailMessage
$msg.To.Add($user)
$msg.From = “EMAILFROM@ADDRESS.COM
$msg.Subject = “Environment DiskSpace Report for $titledate”
$msg.IsBodyHTML = $true
$msg.Body = get-content $diskReport
$smtp.Send($msg)
$body = “Report completed.”

On the server that I’m running this report, I also enabled SMTP and provided an account in which to send the email message from.

Follow this guide to enable SMTP on your server: http://www.itsolutionskb.com/2008/11/installing-and-configuring-windows-server-2008-smtp-server/

Once your powershell script has been finished with all of your settings in place, save it. It should still have that .ps1 extension for powershell.

Open a new notepad document and copy in the following line:

powershell.exe “PATH-TO-REPORT\diskspacereport.ps1”

For example, I had saved my script here: “C:\powershell\diskspacereport.ps1” so my PATH-TO-REPORT will reflect where my script is located.

Save that file as a batch file. I named my file “diskspacereport.bat”.

Now, lets schedule this task to run automatically. Go to START > Administrative Tools > Task Scheduler

Right click in the middle white space of your Task Scheduler Library and Create a New Basic Task. Here, you will need to define what this task is called, when does it occur, and what action does it do. When you get to the actions section, select Start a Program and point it to your batch file we created (diskspacereport.bat). Once complete, you can right click your newly created task and run it. After about 5 minutes, you should receive an email with the results and the HTML file should be visible if you browse to the folder or the server web page.

2 comments

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 )

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

%d bloggers like this: