Here is a quick one. I couldn't find a great way to find the amount of free space which exists on a disk with powershell. I am sure there is a good option, but anway, here is a great solution with uses P/Invoke. This will uses the kernel32 function: GetDiskFreeSpaceEx to figure out how much free space is on a drive. It seems to work pretty well. One catch, P/Invoke in powershell is weird. You pretty much need to go compile the C#.


# Gets the amount of free disk space.
function Get-DiskFreeSpace
        [Parameter(Mandatory = $false)]$Directory = $pwd
        # Name of the P/Invoke we are going to use
        $name = 'GetDiskFreeSpaceEx'

        # The dll the funciton is in
        $dll = 'kernel32.dll'

        # The P/Invoke function definition
        $def = "[DllImport(`"$dll`")]
        public static extern bool $name(string lpDirectoryName,
           out ulong lpFreeBytesAvailable, 
           out ulong lpTotalNumberOfBytes, 
           out ulong lpTotalNumberOfFreeBytes);"

        # First try to see if this already exists
        $type = 'Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.GetStorageFreeType' -as [type]
        # If not, new up a runtime type with this function definition
        if(-not $type)
            $type = Add-Type -MemberDefinition $def -Name "GetStorageFreeType" -PassThru

        $freeBytes = [uint64]0
        $totalBytes = [uint64]0
        $totalFreeBytes = [uint64]0

        # Do the P/Invoke
        $res = $type::GetDiskFreeSpaceEx($Directory, [ref] $freeBytes, [ref] $totalBytes, [ref] $totalFreeBytes)

        # Get the total free bytes
        return $totalFreeBytes