如何从powershell中的Get-ChildItem结果中排除项目列表?

Tar*_*Tar 15 powershell

我希望以递归方式获取路径中的文件列表(实际上是文件数),不包括某些类型:

Get-ChildItem -Path $path -Recurse | ? { $_.Name -notlike "*.cs" -and $_.Name -notlike "*.tt" }
Run Code Online (Sandbox Code Playgroud)

但是我有很多排除列表(仅举几例):

@("*.cs", "*.tt", "*.xaml", "*.csproj", "*.sln", "*.xml", "*.cmd", "*.txt")
Run Code Online (Sandbox Code Playgroud)

如何使用此表单获取列表:

Get-ChildItem -Path $path -Recurse | ? { <# what to put here ?#> }
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 25

您可以Get-ChildItem使用-exclude参数提供排除项:

$excluded = @("*.cs", "*.tt", "*.xaml", "*.csproj", "*.sln", "*.xml", "*.cmd", "*.txt")
get-childitem -path $path -recurse -exclude $excluded
Run Code Online (Sandbox Code Playgroud)


js2*_*010 24

这也有效:

get-childitem $path -recurse -exclude *.cs,*.tt,*.xaml,*.csproj,*.sln,*.xml,*.cmd,*.txt
Run Code Online (Sandbox Code Playgroud)

请注意,-include仅适用于-recurse或路径中的通配符.(实际上它一直在6.1 pre 2中工作)

另请注意,同时使用-exclude和-filter将不会列出任何内容,而不会在路径中列出-recurse或通配符.

-include和-literalpath在PS 5中似乎也有问题.

  • 它与接受的答案有何不同? (4认同)

小智 8

这是使用Where-Object cmdlet的方法:

$exclude = @(".cs", ".tt", ".xaml", ".csproj", ".sln", ".xml", ".cmd", ".txt")
Get-ChildItem -Path $path -Recurse | Where-Object { $exclude -notcontains $_.Extension }
Run Code Online (Sandbox Code Playgroud)

如果您也不想在结果中返回目录,请使用以下命令:

$exclude = @(".cs", ".tt", ".xaml", ".csproj", ".sln", ".xml", ".cmd", ".txt")
Get-ChildItem -Path $path -Recurse | Where-Object { (-not $_.PSIsContainer) -and ($exclude -notcontains $_.Extension) }
Run Code Online (Sandbox Code Playgroud)