调用时
Get-PsDrive | Select Name,Root
我可以看到以下驱动器:
Name Root
---- ----
Alias
C C:
Cert
Env
Function
G \company.comEVPDataGen...
HKCU HKEY_CURRENT_USER
HKLM HKEY_LOCAL_MACHINE
Variable
WSMan
X \serverC$
Z \serverC$
伟大。现在我只想要网络驱动器,即Root
包含\
并且Provider
FileSystem
的驱动器。
所以我尝试了
Get-PSDrive |
where {$_.Provider -match "FileSystem" -and $_.Root -match "\"}
| Select -ExpandProperty Name
但出于某种原因,这包括C
驱动器。这怎么可能?
我也尝试更改为
$_.Root -match "\"
但我得到
解析 "\\" - 模式末尾的非法 \。
和
$_.Root -match "\\"
不返回任何内容。
-match
在右侧采用正则表达式(regex(,在正则表达式语言中,反斜杠是转义字符,指定反斜杠的方法是用另一个反斜杠对其进行转义 - 即\
转换为单个反斜杠,它与驱动器匹配,例如C:
.
您的选择是:
$_ -match '\\' # two escaped backslashes
$_ -match [regex]::Escape('\') # it returns \\ but maybe clearer to a reader what's happening
$_.StartsWith('\') # don't use a regex, use a .Net string method
编辑:
正如我在问题中提到的,当尝试与"\\"匹配时,我没有得到任何返回值。
运行Get-PsDrive Z | Format-List -Property *
,看到类似以下内容:
Used : 89738715136
Free : 29716107264
CurrentLocation :
Name : Z
Provider : Microsoft.PowerShell.CoreFileSystem
Root : Z:
Description :
MaximumSize :
Credential : System.Management.Automation.PSCredential
DisplayRoot : \localhostc$
并且它表明属性root
实际上是驱动器号,UNC 路径称为DisplayRoot
。我不知道为什么,但看起来输出格式化系统正在显示 DisplayRoot 值并将其显示为根值。但这只是在最后的演示步骤中发生的,你不能在脚本中使用它。
@Lieven Keersmaekers使用$_.DisplayRoot -match '\\'
的建议很好。