PowerShell Script to Check Disk Space Usage
Get-PSDrive -PSProvider FileSystem | Select-Object Name, Used, Free, @{Name='Total';Expression={$_.Used + $_.Free}} to check disk space on all drives in PowerShell.Examples
How to Think About It
Algorithm
Code
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{Name='Used(GB)';Expression={[math]::Round(($_.Used/1GB),2)}}, @{Name='Free(GB)';Expression={[math]::Round(($_.Free/1GB),2)}}, @{Name='Total(GB)';Expression={[math]::Round((($_.Used + $_.Free)/1GB),2)}} | Format-Table -AutoSizeDry Run
Let's trace checking disk space on a system with C: drive having 50GB used and 100GB free.
Get all file system drives
Found drive C: with Used=50GB, Free=100GB
Calculate total space
Total = Used + Free = 50GB + 100GB = 150GB
Display results
Output: Name=C, Used=50GB, Free=100GB, Total=150GB
| Drive | Used(GB) | Free(GB) | Total(GB) |
|---|---|---|---|
| C | 50 | 100 | 150 |
Why This Works
Step 1: Get-PSDrive command
The Get-PSDrive -PSProvider FileSystem command lists all drives that store files, like C: or D:.
Step 2: Calculate sizes in GB
We convert bytes to gigabytes by dividing by 1GB and round to 2 decimals for easy reading.
Step 3: Select and display properties
We pick the drive name, used space, free space, and total space, then show them in a neat table.
Alternative Approaches
Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, @{Name='FreeSpace(GB)';Expression={[math]::Round($_.FreeSpace/1GB,2)}}, @{Name='Size(GB)';Expression={[math]::Round($_.Size/1GB,2)}} | Format-Table -AutoSize
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, @{Name='FreeSpace(GB)';Expression={[math]::Round($_.FreeSpace/1GB,2)}}, @{Name='Size(GB)';Expression={[math]::Round($_.Size/1GB,2)}} | Format-Table -AutoSize
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each drive once, so time grows linearly with the number of drives.
Space Complexity
It stores information for each drive, so space also grows linearly with the number of drives.
Which Approach is Fastest?
Using Get-PSDrive is fast and simple for local drives; WMI and CIM methods are slightly slower but provide more detailed info.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-PSDrive | O(n) | O(n) | Quick local disk space check |
| WMI (Get-WmiObject) | O(n) | O(n) | Detailed info, legacy systems |
| CIM (Get-CimInstance) | O(n) | O(n) | Modern systems, faster than WMI |
Format-Table -AutoSize to make the output easy to read in PowerShell.