PowerShell: show free disk space of volumes
Win32_Volume WMI query with calculated properties to list capacity, free space and free percentage.
To display the total capacity, free space and free percentage of every local or removable volume of a server in one command, query the Win32_Volume WMI class and format the result with calculated properties. The original script is by Mohammed A. Wasay, edited by Ali Tajran (alitajran.com); the version below condenses its approach.
$ServerName = 'localhost'
Get-WmiObject -Namespace "root/cimv2" -ComputerName $ServerName -Query "SELECT Name, Capacity, FreeSpace FROM Win32_Volume WHERE Capacity > 0 and (DriveType = 2 OR DriveType = 3)" |
Select-Object -Property Name,
@{ Name = 'Total Capacity (GB)'; Expression = { "{0,19:n2}" -f ($_.Capacity / 1GB) } },
@{ Name = 'Free Space (GB)'; Expression = { "{0,15:n2}" -f ($_.FreeSpace / 1GB) } },
@{ Name = 'Free (%)'; Expression = { [int]($_.FreeSpace * 100 / $_.Capacity) } } |
Sort-Object 'Free (%)' -Descending
How it works
$ServerNameis the machine to query (localhostby default).- The WQL query keeps only volumes with a non-zero capacity and a drive type of 2 (removable disk) or 3 (local disk).
- Three calculated properties expose the capacity in GB, the free space in GB and the free percentage rounded to an integer.
- The sort puts the volumes with the most free space first; use
Sort-Object 'Free (%)'(without-Descending) to see the fullest ones first.
Notes
Get-WmiObjectdoes not exist in PowerShell 7; the equivalent isGet-CimInstance Win32_Volume.- The size columns are formatted as strings (
-f), so the sort is done on the percentage, which stays numeric, and not on those columns.