PowerShell:查找确切的文件夹名称

8

我正在尝试找到一种返回给定文件夹完整路径的方法。问题在于,如果有一个类似命名的文件夹,我的代码会返回多个文件夹。例如,搜索“Program Files”会返回“Program Files”和“Programs Files (x86)”。“Program Files (x86)”不是我要求的,所以我不希望它被返回。我正在使用:

$folderName = "Program Files"
(gci C:\ -Recurse | ?{$_.Name -match [regex]::Escape($folderName)}).FullName

我曾经考虑用-eq代替-match,但是它会返回$false,因为它在比较整个路径。

我想过可能返回所有匹配项,然后让用户选择哪一个是正确的,或者创建一个数组,将路径分解并在每个文件夹名称上执行-eq,然后再次连接路径,但我的数组技能不足,无法使其正常工作。

任何帮助或指针都将不胜感激。

谢谢

这是我使用Frode的东西:

$path = gci -Path "$drive\" -Filter $PartialPath -Recurse -ErrorAction SilentlyContinue #| ?{$_.PSPath -match [regex]::Escape($PartialPath)} 

($path.FullName | gci -Filter $filename -Recurse -ErrorAction SilentlyContinue).FullName
1个回答

10

-match就像在寻找*Program Files*一样。对于类似这样的操作,应该使用Get-ChildItem命令的-Filter参数。它速度更快且不需要使用正则表达式转义等操作。

PowerShell 3版本:

$folderName = "Program Files"
(gci -path C:\ -filter $foldername -Recurse).FullName

PowerShell 2:

$folderName = "Program Files"
gci -path C:\ -filter $foldername -Recurse | Select-Object -Expand FullName

此外,如果您不需要它(例如在此示例中),则不应使用-Recurse

谢谢Frode。我还需要返回特定文件的FullName,因此才使用了GCI。在你的帮助下,我可以这样做:是否可以简化一下? - woter324
$path = gci -Path "$drive" -Filter $PartialPath -Recurse -ErrorAction SilentlyContinue
($path.FullName | gci -Filter $filename -Recurse -ErrorAction SilentlyContinue).FullName. $path = gci -Path "$drive" -Filter $PartialPath -Recurse -ErrorAction SilentlyContinue
($path.FullName | gci -Filter $filename -Recurse -ErrorAction SilentlyContinue).FullName.
- woter324

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接