How-to: List Free Disc space [Get-DriveSpace.ps1]

List the percentage of free disk space for multiple computers.

# Display the drive space on all drives.
# if any have < 20% free space, log to a file for review.

function DriveSpace {
param( [string] $strComputer) 
"$strComputer ---- Free Space (percentage) ----"

# Does the server responds to a ping (otherwise the CIM queries will fail)
$result = Test-connection "$strComputer" -quiet

if ($result) {

   # Get the Disks for this computer
   $colDisks = get-CIMinstance Win32_LogicalDisk -computername $strComputer -Filter "DriveType = 3"

   # For each disk calculate the free space
   ForEach-Object ($disk in $colDisks) {
      if ($disk.size -gt 0) {
         $PercentFree = [Math]::round((($disk.freespace/$disk.size) * 100))
      }
      else {$PercentFree = 0}

       $Drive = $disk.DeviceID
       "$strComputer - $Drive - $PercentFree"

       # if  < 20% free space, log to a file
       if ($PercentFree -le 20) {
          "$strComputer - $Drive - $PercentFree" |
          Out-File -append -filepath "C:\logs\Drive Space.txt"
       }
    }
}
}

Examples

Assuming the script above is saved in the current directory as Get-DriveSpace.ps1:

PS C:\> ./Get-DriveSpace

PS C:\> ./Get-DriveSpace 'Server64'

PS C:\> ForEach-Object ($computer in cat C:\batch\servers.txt) {DriveSpace "$computer"}

“At night, when the sky is full of stars and the sea is still you get the wonderful sensation that you are floating in space” ~ Natalie Wood.

Related PowerShell Cmdlets

pshInfo - List Ram, Disk Space, Service pack, Uptime.


 
Copyright © 1999-2024 SS64.com
Some rights reserved