首页 > 解决方案 > Get-ChildItem 后的快速过滤

问题描述

有了PowerShell 5.1新的.NET framework,终于可以使用Get-ChildItem -Path "\\?\C:\MyPath".

在下面的代码中,我们尝试过滤掉特定目录(以及目录本身)中的文件和文件夹,因为我们对它们不感兴趣。

这段代码运行良好,但我们想知道是否有更好或更快的方法来代替构建一个长的正则表达式字符串?

如果数组$IgnoredFolders变得很长,则可能需要更多时间-notmatch来做出决定。我不是正则表达式方面的专家,他们可能会变成多长时间,所以欢迎任何反馈。

<#
# Path
    Folder A         
        File folder A.txt
    Folder B         
        File folder B.txt
    Folder C         
        File folder C.txt

    File root A.txt  
    File root B.txt  
#>

$Path = 'S:\testFolder'

$IgnoredFolders = @(
    "$Path\Folder B"
    "$Path\Folder C"
)

$RegexIgnoredFolders = $IgnoredFolders.ForEach({
    [Regex]::Escape("\\?\$_")
}) -join '|'

@(Get-ChildItem -LiteralPath "\\?\$Path" -Recurse).Where({ 
    $_.FullName -notmatch $RegexIgnoredFolders
}) | select fullname

这段代码的输出是:

"$Path\Folder A"              
"$Path\File root A.txt"     
"$Path\File root B.txt"          
"$Path\Folder A\File folder A.txt"

标签: regexpowershellfilter

解决方案


推荐阅读