3

I have to create a script which performs some operations in a given folder, but it must include a prior check if there is enough space left before starting the operations. The folder name is an UNC path, e.g. \\example-server\share1\folder\subfolder\. How can I get the amount of free space in the folder?

Things that I tried so far:

  • I read that I can use gwmi, Get-CimInstance, Get-Volume and Get-PSDrive to get information about a volume, but I don't know how to determine the volume where the folder is stored.

  • I tried using this interesting-looking function, GetDiskFreeSpaceEx in my script but sadly it returned with Success=false and an empty value for "Free".

  • if you're just wanting to get the size of a folder, this is what i use https://github.com/gangstanthony/PowerShell/blob/master/Get-FolderSize.ps1 – Anthony Stringer Apr 08 '19 at 19:34

2 Answers2

5

The following may not be the best solution, but it could work:

# Determine all single-letter drive names.
$takenDriveLetters = (Get-PSDrive).Name -like '?'

# Find the first unused drive letter.
# Note: In PowerShell (Core) 7+ you can simplify [char[]] (0x41..0x5a) to
#       'A'..'Z'
$firstUnusedDriveLetter = [char[]] (0x41..0x5a) | 
  where { $_ -notin $takenDriveLetters } | select -first 1

# Temporarily map the target UNC path to a drive letter...
$null = net use ${firstUnusedDriveLetter}: '\\example-server\share1\folder\subfolder' /persistent:no
# ... and obtain the resulting drive's free space ...
$freeSpace = (Get-PSDrive $firstUnusedDriveLetter).Free
# ... and delete the mapping again.
$null = net use ${firstUnusedDriveLetter}: /delete

$freeSpace # output

net use-mapped drives report their free space, while those established with New-PSDrive as PowerShell-only drives do not, whereas they do if you create them with -PersistThanks, zett42. (which makes the call equivalent to net use; from scripts, be sure to also specify -Scope Global, due to the bug described in GitHub issue #15752).

I've omitted error handling for brevity.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

As per mklement0 example above, Get-PSDrive does not return the correct free space value when a quota is applied to the share and/or subfolder within the share. Instead, use the .NET Class System.IO.DriveInfo and the AvailableFreeSpace property:

    $freespace = (New-Object -TypeName System.IO.DriveInfo `
                 -ArgumentList $firstUnusedDriveLetter).AvailableFreeSpace