PowerShell: Get Disk Free Space

PowerShell Get Disk Free Space

Knowing the exact size and free space of all system disks is often useful.

The information can be used for ongoing monitoring of available resources or as a “one-off” when you’re installing new software.

The below PowerShell function, Get-DiskSize, will create an object that carries the disk free space information.

As the information is wrapped in an object you can easily do further processing of the information.

The code is nested in a PowerShell function so you can easily port it to your own code.

  1. Function Get-DiskSize {
  2. $Disks = @()
  3. $DiskObjects = Get-WmiObject -namespace "root/cimv2" -query "SELECT Name, Capacity, FreeSpace FROM Win32_Volume"
  4. $DiskObjects | % {
  5. $Disk = New-Object PSObject -Property @{
  6. Name = $_.Name
  7. Capacity = [math]::Round($_.Capacity / 1073741824, 2)
  8. FreeSpace = [math]::Round($_.FreeSpace / 1073741824, 2)
  9. FreePercentage = [math]::Round($_.FreeSpace / $_.Capacity * 100, 1)
  10. }
  11. $Disks += $Disk
  12. }
  13. Write-Output $Disks | Sort-Object Name
  14. }
  15. Get-DiskSize | ft Name,@{L='Capacity (GB)';E={$_.Capacity}},@{L='FreeSpace (GB)';E={$_.FreeSpace}},@{L='FreePercentage (%)';E={$_.FreePercentage}}

The output from the code will look similar to this:

Name Capacity (GB) FreeSpace (GB) FreePercentage (%) ---- ------------- -------------- ------------------ \\?\Volume{6e1a788e-0000-0000-0000-303de3000000}\ 0.85 0.28 32.3 \\?\Volume{ab58b645-acea-11e4-81a2-806e6f6e6963}\ 1.46 1.12 76.3 C:\ 907.49 207.16 22.8 Q:\ 21.7 8.2 37.8

Use the function and Disks object creatively as you see fit. Here’s an example to get you started:

PS C:\> $SysDisk = Get-DiskSize | ? {$_.Name -eq 'c:\'} PS C:\> $SysDisk Capacity Name FreePercentage FreeSpace -------- ---- -------------- --------- 907.49 C:\ 22.8 207.04 PS C:\> Write-Host Drive $SysDisk.Name has $SysDisk.FreePercentage percent free disk Drive C:\ has 22.8 percent free disk
Did you like this post? Maybe your friends will too!