How-To – Check diskspace using PowerShell

Sometimes it’s useful to quickly get an idea of certain usage statistics from a number of servers. Without monitoring and capacity management systems in place it may be difficult to capture information such as disk usage, fragmentation etc.

Rather than logging into each server and manually gather the information, why not automate the task using WMI and PowerShell? The script below will connect to each server in the list ($compList) and determine the free disk space and volume fragmentation.

$compList = "LONDON", "BRISBANE"
$DiskResults = @()
foreach ($computerName in $compList)
{
  Write-Host $computerName
  $objDisks = Get-WmiObject -Computername $computerName -Class win32_logicaldisk | Where-Object { $_.DriveType -eq 3 }
  ForEach( $disk in $objDisks )
  {
    $diskFragmentation = "Unknown"
    try
    {
      $objDisk = Get-WmiObject -Computername $computerName -Class Win32_Volume -Filter "DriveLetter='$($disk.DeviceID)'"
      $objDefrag = $objDisk.DefragAnalysis()
      $objDefragAnalysis = $objDefrag.DefragAnalysis;
      $diskFragmentation = $objDefragAnalysis.TotalPercentFragmentation
    }
    catch{}
    $ThisVolume = "" | select ServerName,Volume,Capacity,FreeSpace,Fragmentation
    $ThisVolume.ServerName = $computerName
    $ThisVolume.Volume = $disk.DeviceID
    $ThisVolume.Capacity = $([Math]::Round($disk.Size/1073741824,2))
    $ThisVolume.FreeSpace = $([Math]::Round($disk.FreeSpace/1073741824,2))
    $ThisVolume.Fragmentation = $diskFragmentation
    $DiskResults += $ThisVolume
  }
}
$DiskResults | ft

This could easily be extended to capture windows reliability information using Win32_ReliabilityRecords to determine if servers have crashed recently or other information. Check back for a future post about that.

Published by

Dave Hope

Dave is a Principal Software Analyst for a UK based retirement developer, in his spare time he enjoys digital photography and rock climbing.

One thought on “How-To – Check diskspace using PowerShell”

Leave a Reply

Your email address will not be published. Required fields are marked *