Creating Server Disk Usage Report with PowerShell

Introduction

Regularly monitoring server disk usage is crucial in the daily management of operating systems. Despite numerous tools available in the market for monitoring system health, in this article, I will explain the steps to create a server disk usage report using PowerShell in a simple way. You can customize the script according to your environment.

First Steps

First, we will define the function to be used in our script. The ConvertTo-GB function takes the size in bytes and returns it converted to gigabytes. This will help us create more readable reports.
# Function to convert bytes to GB
function ConvertTo-GB {
    param([int64]$size)
    $size / 1GB
}

Getting Server and Drive Information

Next, we will determine the servers to monitor for disk usage, specify a drive letter to exclude from the reports, and define specific threshold values in the reports.
Here, the value we define as $FSGBThreshold specifies when the remaining free space in GB should be considered after this value.
# List of servers
$servers = "Server01", "Server02", "Server03"

# Excluded drive letter
$excludedDrive = "H:" 

# Free Space (GB) threshold value
$FSGBThreshold = 50
# Free Space Percentage (second level)(%) threshold value
$FSPThresholdOrange = 20
# Free Space Percentage (first level)(%) threshold value
$FSPThresholdRed = 10

In this example, the relevant color-coding rules in the report are triggered if there is less than or equal to 50 GB of remaining free space. Similarly, the $FSPThresholdOrange value allows us to set the warning threshold, and $FSPThresholdRed allows us to set the critical threshold in percentage.

Generate HTML Report

We will use the template below to create an HTML report. This report will contain individual information for each server and disk, providing visual information with color codes.
# Create HTML report
$htmlReport = @"
<style>
<!DOCTYPE html>
<html>
<head>
    <style>
        table {
            font-family: Arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
        .red {
            background-color: #ff8080; /* Red */
        }
        .orange {
            background-color: #ffb366; /* Orange */
        }
        .green {
            background-color: #b3ffcc; /* Green */
        }
        .yellow {
            background-color: #FFFACD; /* Yellow */
        }
    </style>
</head>
<body>

<h2>Server Disk Usage Report</h2>

<table>
    <tr>
        <th>Server</th>
        <th>Drive</th>
        <th>Volume Name</th>
        <th>File System</th>
        <th>Total Size (GB)</th>
        <th>Free Space (GB)</th>
        <th>Used Space (GB)</th>
        <th>Free Space Percentage</th>
    </tr>
"@

Processing Server and Disk Information

We will use WMI (Windows Management Instrumentation) to retrieve server and disk information. 

What is WMI?

WMI (Windows Management Instrumentation) is a management infrastructure by Microsoft found in Windows operating systems. WMI provides a framework for system and network management, used for remote management and monitoring operations. It offers an interface standardizing the management and monitoring functionalities of Windows and is commonly employed in various programming languages like PowerShell and other management tools.
We will retrieve the necessary information for each disk and determine color codes.

Determining Color Codes and Filling the Report

We will determine color codes based on predefined threshold values for each disk and fill out the report.
This code defines two different color classes ($FSPcolorClass and $FSGBcolorClass) based on specific conditions. If Free Space(%) is below 10% and at the same time the Free Space (GB) is below 50GB, then the cell color becomes "red"; otherwise, it becomes "yellow". This is because when the disk size is very large, even a 10% free space value corresponds to a significant GB space. For example, for a 1 TB disk, a 10% free space is equivalent to 100 GB, so the threshold limit is determined in GB to evaluate it as a critical level. 
Similarly, if Free Space(%) is below 20% and at the same time the Free Space (GB) is below 50GB, then the cell color becomes "orange"; otherwise, it becomes "yellow". If none of these conditions are met, meaning there is more than 20% free space in the total disk size, the color class becomes "green". This code is used to provide visual feedback by determining color classes based on disk usage status.
foreach ($server in $servers) {
    $diskInfo = Get-WmiObject -ComputerName $server -Query "SELECT * FROM Win32_LogicalDisk"

    foreach ($disk in $diskInfo) {
        $driveLetter = $disk.DeviceID

        # Skip excluded drive
        if ($driveLetter -eq $excludedDrive) {
            continue
        }
        $volumeName = $disk.VolumeName
        $fileSystem = $disk.FileSystem
        $totalSize = [math]::Round((ConvertTo-GB $disk.Size),1)
        $freeSpace = [math]::Round((ConvertTo-GB $disk.FreeSpace),1)
        $usedSpace = $totalSize - $freeSpace
        $freeSpacePercentage = [math]::Round(($freeSpace / $totalSize) * 100, 2)
        $FSGBcolorClass = ''
        $FSPcolorClass = ''
        if ($freeSpacePercentage -le $FSPThresholdRed) 
        {
            if($freeSpace -le $FSGBThreshold)
            {
                $FSPcolorClass = 'red'
                $FSGBcolorClass = 'transparent'
            }
            else
            {
                $FSPcolorClass = 'yellow'
                $FSGBcolorClass = 'green'
            }
        }
        elseif ($freeSpacePercentage -le $FSPThresholdOrange) 
        {
            if($freeSpace -le $FSGBThreshold)
            {
                $FSPcolorClass = 'orange'
                $FSGBcolorClass = 'transparent'
            }
            else 
            {
                $FSPcolorClass = 'yellow'
                $FSGBcolorClass = 'green'
            }
        }
        else
        {
            $FSPcolorClass = 'green'
        }

Completing the Report

Finally, we will add the information obtained for each disk to the report.
	$htmlReport += @"
    <tr>
        <td>$server</td>
        <td>$driveLetter</td>
        <td>$volumeName</td>
        <td>$fileSystem</td>
        <td>$totalSize</td>
        <td class="$FSGBcolorClass">$freeSpace</td>
        <td>$usedSpace</td>
        <td class="$FSPcolorClass">$freeSpacePercentage%</td>
    </tr>
    </table>
</body>
</html>
	"@
    }
}

Sending the Report via Email

To send the completed report as an email, we will use the code block below.

    # Mail configuration
$smtpServer = "smtp.yourdomain.com"
$smtpFrom = "your-email@yourdomain.com"
$smtpTo = "recipient-email@theirDomain.com"
$messageSubject = "Server Disk Usage Report"
$messageBody = $htmlReport
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$mailmessage = New-Object Net.Mail.MailMessage($smtpFrom, $smtpTo, $messageSubject, $messageBody)
$mailmessage.IsBodyHTML = $true

# Send the mail
try
{
    $smtp.Send($mailmessage)
    Write-Host "Server Disk usage report sent successfully."
}
catch 
{
    Write-Host "Server Disk usage report could not sent to:$smtpTo address"
}
    
This code performs the following steps:
  1. Mail Configuration: Includes configuration information for email sending, such as SMTP server, sender email address, recipient email address, email subject, and email body. You need to define the relevant fields according to your system.
  2. Create SMTP Client: Configures the SMTP client by creating an instance of the Net.Mail.SmtpClient class.
  3. Create Email Message: Configures the email message by creating an instance of the Net.Mail.MailMessage class. It specifies that the email body is in HTML format by setting the IsBodyHTML property to true.
  4. Email Sending: Sends the email using the Send method. If the sending is successful, a success message is displayed. If there is an error during sending, the catch block is executed, and an error message is displayed.

Saving the Report to File

To save the HTML report to a file, you can use the following code.
# Save HTML report to file
try
{
    $htmlReport | Out-File -FilePath $htmlFilePath
    Write-Host "Disk usage report generated successfully. Path: $htmlFilePath"
}
catch 
{
    Write-Host "Disk usage report could not be generated"
}
        

Conclusion

You can use this PowerShell script to monitor, report, and receive alerts for the disk usage of your specified servers. Having the report in HTML format facilitates easy sharing and reading of information.

I hope this article guides you in monitoring and reporting server disk usage using PowerShell. If you have any questions or suggestions, please share them in the comments section. Happy coding!


Türkçe makaleye erişmek için lütfen tıklayınız..

Yorumlar

Bu blogdaki popüler yayınlar

Reporting Exchange Mail Traffic and Login Statistics with PowerShell

Exchange Server 2016/2019 Sertifika Yenileme

Bulk Resetting Active Directory User Passwords