Monitoring disk space utilization of server(s) is a critical and important job for any administrator. Keeping things organized might improve application availability and server availability. Being a database administrator for 10 years, I have faced and handled/managed lot of issues with disk space. This article takes us through the in-detail steps to read each drive and report every drive details based on threshold values. The output is integrated with HTML tags. The step by step process quickly take us through the disk space utilization details of the server(s). You'll basically feed a list of servers to watch over, and it will report back on these for you, meaning you could also use it as a more general "daily server disk space report"
↑ Return to Top
This article talks about the use of credentials. The credentials can be used to query external servers which has a trust relationship between the domains. Also, list various methods to secure the password. The process iterates through a list of servers and drives that you have listed in a CSV file. Checking for disk space status of every listed drive and its status may fall under one of the four statuses that are defined as critical, warning, low and good. The nice thing about this script is that it will consolidate health status of each listed disks and gives a summary that needs your attention (you set the threshold as per requirement because the size of the drive may vary from server to server).
Get-credential always pop-up dialog box for entering a password, however, you can save your securestring password to a file or directly feed the password. The problem with this is that the password will be exposed to anyone with access to the file.
The Get-Credential displays a window to enter credential details. This will appear every time when you run the script.The $credential variable store the user name and password. It's then fed to the respective queries for further processing.
clear
$credential = Get-Credential
foreach ( $args in get-Content c:\server.txt ) {
get-WmiObject win
32
_logicaldisk -Credential $credential -ComputerName $args -Filter
"Drivetype=3"
|
ft SystemName,DeviceID,VolumeName,@{Label=
"Total SIze"
;Expression={$_.Size /
1
gb -as [int] }},@{Label=
"Free Size"
;Expression={$_.freespace /
gb -as [int] }} -autosize
}
The password is hard coded in the script. Of course, the problem with this is that your password will be exposed to anyone with access to the script file.
$User =
'hqnt\abcd'
$Pass = ConvertTo-SecureString
'abcd@2015'
-AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$Pass
_logicaldisk -ComputerName $args -Credential $Credentials -Filter
First, Password has to be written to a file
ps:\>read-host -AsSecureString |ConvertFrom-SecureString |Out-File C:\SecurePassword.txt
Second, The credentials are read from the file using PSCredential class. You don't need to re-enter the password over and over again.
'hqnt\abcdv'
$pass= cat C:\passwordstring.txt |ConvertTo-SecureString
_logicaldisk -ComputerName $args -Credentials $cred -Filter
You don't need to use the credential parameter in any of the cmdlet execution.
_logicaldisk -ComputerName $args -Filter
PosH- DiskSpace -CSV Input and HTML Output
The template of server.csv is given below. Change the content as per your requirement/environment
Server,Drive,LowTh,WarnTh,CritTh
HQDBSP00
8
,E:,
,
5
3
,F:,
20
18
,G:,
HQSPDB99
01
HQSPDB09
HQSPDB80
The below code defines the output file location and filename. Change the location or filename as per your requirement.
$filename=
"c:\freespace.htm" New-Item -ItemType file $freeSpaceFileName -Force
New-Item -ItemType file $freeSpaceFileName -Force
The New-item cmdlet creates an item.
-Force
Forces this cmdlet to create an item that writes over an existing read-only item. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.
The Add-Content cmdlet is used to prepare CSS HTML file. The cmdlet is to append the data to a text file. In this case, it's going to be an HTML file.
There are two ways of preparing HTML output. One is through ConvertTo-HTML and using cssri parameter which accepts style sheet path as its input and another one is through manually defining the CSS tags and building an HTML file. It's like building an HTML file with values and tags to be displayed in a file. If one has a little bit of knowledge over CSS will help a lot in this case.
The below code has modularized for simple understanding and easy to enhance the code if one has to make any changes to a template.
The following four functions are used to generate the HTML document:
For example,
<!DOCTYPE html>
<
html
>
head
style
td {
font-family: Tahoma;font-size: 11px;
border-top: 1px solid darkGray;border-right: 1px solid darkGray;border-bottom: 1px solid darkGray;border-left: 1px solid darkGray;
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;
-->
</
body
h2
>The Sample data</
table
tr
><
th
>Firstname</
>Lastname</
td
>Peter</
>Geelan</
></
> <
>Ed</
>Price</
The $status variable defines the color combination for each drive status
Function writeHtmlHeader
{
param($fileName)
$date = ( get-date ).ToString(
'yyyy/MM/dd'
)
Add-Content $fileName
"<html>"
"<head>"
"<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
'<title>DiskSpace Report</title>'
add-content $fileName
'<STYLE TYPE="text/css">'
"<!--"
"td {"
"font-family: Tahoma;"
"font-size: 11px;"
"border-top: 1px solid darkGray;"
"border-right: 1px solid darkGray;"
"border-bottom: 1px solid darkGray;"
"border-left: 1px solid darkGray;"
"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;"
""
"-->"
"</style>"
add-Content $fileName
"</head>"
"<body>"
"<table width='100%'>"
"<tr bgcolor='cadetBlue'>"
"<td colspan='9' height='25' width=5% align='left'>"
"<font face='tahoma' color='black' size='5'><center><strong>DiskSpace Report - $date</strong></center></font>"
"</td>"
"</tr>"
# Function to write the HTML Header to the file
Function writeTableHeader
"<tr bgcolor=cadetBlue>"
"<td><b>Server</b></td>"
"<td><b>Drive</b></td>"
"<td><b>Drive Label</b></td>"
"<td><b>Total Capacity(GB)</b></td>"
"<td><b>Used Capacity(GB)</b></td>"
"<td><b>Free Space(GB)</b></td>"
"<td><b>FreeSpace % </b></td>"
"<td><b>Status </b></td>"
Function writeHtmlFooter
"</body>"
"</html>"
Function writeDiskInfo
param($fileName,$server,$DeviceID,$VolumeName,$TotalSizeGB,$UsedSpaceGB,$FreeSpaceGB,$FreePer,$status)
if ($status -eq
'warning'
"<tr>"
"<td >$server</td>"
"<td >$DeviceID</td>"
"<td >$VolumeName</td>"
"<td >$TotalSizeGB</td>"
"<td >$UsedSpaceGB</td>"
"<td >$FreeSpaceGB</td>"
"<td bgcolor='darkGoldenrod' >$FreePer</td>"
"<td >$status</td>"
elseif ($status -eq
'critical'
"<td bgcolor='red' >$FreePer</td>"
'low'
"<td bgcolor='aquamarine' >$FreePer</td>"
'good'
"<td bgcolor='darkGreen' >$FreePer</td>"
The next part is connectivity test using Test-Connection cmdlet. It does a basic connectivity test and once it's successful it goes to the next steps.
The last part of the code calls the function writeDiskInfo. This function used to prepare HTML body using HTML tags.
<# .SYNOPSIS Name : Disk Space Utilization Report (Get-DiskSpaceHTML.ps1) Description : Get disk space usage information from remote server(s) with WMI and output HTML file Author : Prashanth Jayaram * Select list of servers from a CSV file * Get remote Servers information with WMI and Powershell : * Disk (Disk type, letter, capacity in GB, free space in GB, % free , Status + display a HTML output) .INPUT .csv file with servers to activate .OUTPUTS Console outputs : You can alter the code to write the data to file or console .NOTES Version: 1.0 Author: Prashanth Jayaram Creation Date: 2016-26-09 Purpose/Change: Initial script development .EXAMPLE .\Get-DiskSpaceHTML.ps1 #>
.SYNOPSIS
Name : Disk Space Utilization Report (Get-DiskSpaceHTML.ps1)
Description : Get disk space usage information from remote server(s) with WMI and output HTML file
Author : Prashanth Jayaram
* Select list of servers from a CSV file
* Get remote Servers information with WMI and Powershell :
* Disk (Disk type, letter, capacity in GB, free space in GB, % free , Status + display a HTML output)
.INPUT
.csv file with servers to activate
.OUTPUTS
Console outputs : You can alter the code to write the data to file or console
.NOTES
Version: 1.0
Author: Prashanth Jayaram
Creation Date: 2016-26-09
Purpose/Change: Initial script development
.EXAMPLE
.\Get-DiskSpaceHTML.ps1
#>
#############################################################################
# Check disk space usage and generate HTML file
# Author: Prashanth Jayaram
# Date:
9
/
23
2016
##############################################################################
#########################################################################################
#DirectoryPath - Make sure you have enough rights to write to that path
# color combination refer this link http://www.w/
schools.com/tags/ref_colornames.asp
$freeSpaceFileName =
"C:\FreeSpace.htm"
# Getting the freespace info using WMI
#Get-WmiObject win
_logicaldisk | Where-Object {$_.drivetype -eq
-OR $_.drivetype -eq
2
} | format-table DeviceID, VolumeName,status,Size,FreeSpace | Out-File FreeSpace.txt
"table {"
"border: thin solid black;"
"table { "
"border-spacing: 10 px;"
"border-collapse: separate;"
writeHtmlHeader $freeSpaceFileName
writeTableHeader $freeSpaceFileName
Import-Csv C:\server.csv|%{
$cserver = $_.Server
$cdrivelt = $_.Drive
$clowth = $_.LowTh
$cwarnth = $_.WarnTh
$ccritth = $_.CritTh
$status=
''
if(Test-Connection -ComputerName $cserver -Count
-ea
0
) {
$diskinfo= Get-WmiObject -Class Win
_LogicalDisk -ComputerName $cserver -Filter
"DeviceID='$cdrivelt'"
ForEach ($disk in $diskinfo)
If ($diskinfo.Size -gt
) {$percentFree = [Math]::round((($diskinfo.freespace/$diskinfo.size) *
100
))}
Else {$percentFree =
#Process each disk in the collection and write to spreadsheet
$server=$disk.__Server
$deviceID=$disk.DeviceID
$Volume=$disk.VolumeName
$TotalSizeGB=[math]::Round(($disk.Size /
GB),
$UsedSpaceGB=[math]::Round((($disk.Size - $disk.FreeSpace)/
$FreeSpaceGB=[math]::Round(($disk.FreeSpace /
$FreePer=(
"{0:P}"
-f ($disk.FreeSpace / $disk.Size))
#Determine if disk needs to be flagged for warning or critical alert
If ($percentFree -le $ccritth) {
$status =
"Critical"
} ElseIf ($percentFree -gt $ccritth -AND $percentFree -le $cwarnth) {
"Warning"
ElseIf ($percentFree -ge $cwarnth -AND $percentFree -lt $clowth) {
"Low"
} Else {
"Good"
write-host $server $DeviceID $Volume $TotalSizeGB $UsedSpaceGB $FreeSpaceGB $FreePer $status
writeDiskInfo $freeSpaceFileName $server $DeviceID $Volume $TotalSizeGB $UsedSpaceGB $FreeSpaceGB $FreePer $status
Add-Content $freeSpaceFileName
"</table>"
writeHtmlFooter $freeSpaceFileName
To initiate email message we'll use.Net class library System.Net.Mail.MailMessage. This basically uses SMTP client to sent mail messages.The mail body can be HTML or string or an attachment. In this case, we are sending an email attachment.
$email = New-Object System.Net.Mail.MailMessage
Create the new MailMessage object $email, using this variable assign to and From addresses, subject line and body of an email.
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Subject = $subject
$email.Body = $body
To add an email attachment one has to invoke System.Net.Mail.Attachment class
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
The object has been instantiated by adding the attachment
$email.Attachments.Add($emailAttach)
Initiate sending email. The final step is to create the SmtpClient object and send the mail message.
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
#initate message
#For this we'll use .Net class library System.Net.Mail.MailMessage. This basically uses SMTP client to sent mail messages.The mail body can be HTML or string or an attachment. In this case we are sending email attachment.
#we create the new MailMessage object $email, using this variable assign to and From addresses, subject line and body of email.
# initiate email attachment, This can be done using System.Net.Mail.Attachment class.
#Add
the attachment to an object
#initiate sending email . The final step is to create the SmtpClient object and send the mail message.
#Call Function
$message = @"
Hi Team,
The Disk Space Usage details Report.
Autogenerated Email!!! Please do not reply.
Thank you,
xyz.com
"@
$date=get-date
sendEmail -emailFrom $fromEmail -emailTo $ToEmail -subject
"Disk Space Usage Report -$($date)"
-body $message -smtpServer $SMTPMail -filePath $filename
Function sendEmail
param($from,$to,$subject,$smtphost,$htmlFileName)
#Assigning multiple recipients to $recipient string
[string]$recipients=
"$to"
#Reading the content of HTML source
$body = Get-Content $htmlFileName
$body = New-Object System.Net.Mail.MailMessage $from, $recipients, $subject, $body
#setting the message body to be HTML.
$body.isBodyhtml = $true
$smtpServer = $MailServer
$smtp = new-object Net.Mail.SmtpClient($smtphost)
$smtp.Send($body)
PoSH : Disk Space Monitoring Guide