我正在尝试创建一个函数来返回以 MB 为单位的可用驱动器空间量。该函数将路径名作为参数,并且必须处理挂载点。我的驱动器设置如下:
所以我想做一些类似的事情:
function Get-FreeSpace {
param (
$path
);
# iterate through and find the volume, detect if in a mount point and return free space
#
return [int]$freeSpace;
}
我曾考虑在我的函数中使用这个数组作为起点,但我被卡住了。
$vols = Get-WMIObject Win32_Volume -filter "DriveType=3" -computer $computerName | Select Caption,DriveLetter,Label,@{Name="DiskSize(GB)";Expression={[decimal]("{0:N1}" -f($_.capacity/1gb))}},@{Name="PercentFree(%)";Expression={"{0:P2}" -f(($_.freespace/1mb)/($_.capacity/1mb))}}
$vols
正在返回 System.Array
的 PSCustomObject
类型。因此,如果我通过以下路径传递函数:G:\Data\My\Test\Path
G:\Data
它将找到
G:\Data
的可用空间挂载点。如果我通过了
G:\Some\Other\Path
,它将返回 G:\
的可用空间驾驶。我想像这样使用它:$freeSpace = Get-FreeSpace "G:\Some\Other\Path"
我将不胜感激任何帮助。
最佳答案
尝试这个:
function Get-FreeSpace {
Param(
$path
);
if ($path[-1] -ne '\') { $path += '\' }
$filter = "DriveType=3 And Name='$($path -replace '\\', '\\')'"
$free = Get-WmiObject Win32_Volume -Filter $filter |
Select-Object -Expand FreeSpace
return ($free / (1024*1024))
}
您需要将
$path
中的反斜杠加倍,因为它们必须为 WMI 查询进行转义。为此(看起来令人困惑)您必须替换 '\\'
与 '\\'
,因为第一次出现是一个正则表达式,其中反斜杠必须被转义,而第二次出现是一个带有双反斜杠的字符串文字。更新:
要匹配部分路径,您可以使用
-like
运算符(operator):function Get-FreeSpace {
Param(
$path
);
$free = Get-WmiObject Win32_Volume -Filter "DriveType=3" |
Where-Object { $path -like "$($_.Name)*" } |
Sort-Object Name -Desc |
Select-Object -First 1 FreeSpace |
ForEach-Object { $_.FreeSpace / (1024*1024) }
return ([int]$free)
}
Where-Object
子句选择部分路径匹配的所有挂载点 $path
,以及随后的 Sort-Object | Select-Object
选择匹配时间最长的那个。
关于powershell - 在 powershell 中获取提供的驱动器路径的可用空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248325/