powershell

How to get the remaining amount of storage space in a shared folder


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:


Solution

  • 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.