Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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

like image 779
Abrissbirne 66 Avatar asked Sep 09 '25 14:09

Abrissbirne 66


1 Answers

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.

like image 178
mklement0 Avatar answered Sep 12 '25 05:09

mklement0