Snippet #2 – Checking for free disk space with PowerShell

Inspired by Dan’s last post, I thought I would share some more PowerShell goodness. A very quick one to start with: How to check for free disk space with PowerShell.

As you would expect with PowerShell its amazingly simple. Here is the function:

Function GetFreeDiskSpace([string]$DriveLetter, [string]$Measurement)

{

$Drives=Get-WmiObject -Class Win32_LogicalDisk

foreach($Drive in $Drives)

{

If ($Drive.Name -eq $DriveLetter)

{

[int]$GLOBAL:Freespace=$Drive.FreeSpace/“1$Measurement

}

}

}

The function simply queries the WMI LogicalDisk class and then converts the fresspace to GB, MB or KB. For example, if you want to find out how much free disk space is available for the c:\ in Gigabytes, you would call the function as follows:

GetFreeDiskSpace “C:” “GB”

write-host “Freespace = $Freespace

That’s all for now 🙂

Advertisements