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

时间:2013-10-06 10:47:49

标签: powershell

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

Get-ChildItem -Path $path -Recurse | ? { $_.Name -notlike "*.cs" -and $_.Name -notlike "*.tt" }

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

@("*.cs", "*.tt", "*.xaml", "*.csproj", "*.sln", "*.xml", "*.cmd", "*.txt")

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

Get-ChildItem -Path $path -Recurse | ? { <# what to put here ?#> }

5 个答案:

答案 0 :(得分:22)

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

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

答案 1 :(得分:18)

这也有效:

get-childitem $path -recurse -exclude *.cs,*.tt,*.xaml,*.csproj,*.sln,*.xml,*.cmd,*.txt

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

另请注意,使用-exclude和-filter都不会列出任何内容,路径中没有-recurse或通配符。

在PS 5中,

-include和-literalpath似乎也有问题。

答案 2 :(得分:5)

以下是使用Where-Object cmdlet执行此操作的方法:

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

如果您不希望在结果中返回目录,请使用:

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

答案 3 :(得分:1)

Set-Location C:\

$ExcludedcDirectory = "Windows|Program|Visual|Trend|NVidia|inet"
$SearchThis = Get-ChildItem -Directory | where Name -NotMatch $ExcludedcDirectory

$OutlookFiles = foreach ($myDir in $SearchThis) {    
    $Fn = Split-Path $myDir.fullname
    $mypath = "Get-ChildItem -Path $Fn\*.pst, *.ost -Recurse -ErrorAction SilentlyContinue" 

     Invoke-Expression "$mypath"
}
$OutlookFiles.FullName

答案 4 :(得分:0)

您可以使用Where-Object这样操作:

Get-ChildItem -Path $path -Recurse | Where-Object { $_.Extension -notin @("*.cs", "*.tt", "*.xaml", "*.csproj", "*.sln", "*.xml", "*.cmd", "*.txt")}