【问题标题】:How to get the remaining amount of storage space in a shared folder如何获取共享文件夹中的剩余存储空间
【发布时间】:2022-03-15 00:04:11
【问题描述】:

我必须创建一个在给定文件夹中执行某些操作的脚本,但它必须包括在开始操作之前是否有足够的空间剩余的事先检查。文件夹名称是 UNC 路径,例如\\example-server\share1\folder\subfolder\。如何获取文件夹中的可用空间量?

到目前为止我尝试过的事情:

  • 我读到我可以使用gwmiGet-CimInstanceGet-Volume Get-PSDrive 来获取有关卷的信息,但我不知道如何确定存储文件夹的卷。

  • 我尝试在我的脚本中使用 this interesting-looking function, GetDiskFreeSpaceEx,但遗憾的是它返回 Success=false 并且“免费”的值为空。

【问题讨论】:

标签: powershell


【解决方案1】:

以下可能不是最好的解决方案,但它可以工作:

# 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 驱动器报告其可用空间,而使用 New-PSDrive 建立的驱动器作为 PowerShell-only 驱动器 不报告,而如果您使用 -Persist 创建它们,它们会报告其可用空间谢谢zett42(这使得调用等效于net use;由于GitHub issue #15752 中描述的错误,从脚本中,请务必同时指定-Scope Global)。

为简洁起见,我省略了错误处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 2017-09-20
    • 2019-10-15
    • 2015-08-17
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多