35
votes

I want to get list of files (actually number of files) in a path, recursively, excluding certain types:

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

but I have a long list of exclusions (to name a few):

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

How to get the list using this form:

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

?

5

5 Answers

50
votes

This works too:

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

Note that -include only works with -recurse or a wildcard in the path. (actually it works all the time in 6.1 pre 2)

Also note that using both -exclude and -filter will not list anything, without -recurse or a wildcard in the path.

-include and -literalpath also seem problematic in PS 5.

There's also a bug with -include and -exclude with the path at the root "\", that displays nothing. In unix it gives an error.

33
votes

You can supply exclusions to Get-ChildItem with the -exclude parameter:

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

Here is how you would do it using a Where-Object cmdlet:

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

If you do not want directories to be returned in the results as well, then use this:

$exclude = @(".cs", ".tt", ".xaml", ".csproj", ".sln", ".xml", ".cmd", ".txt")
Get-ChildItem -Path $path -Recurse | Where-Object { (-not $_.PSIsContainer) -and ($exclude -notcontains $_.Extension) }
2
votes
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
0
votes

You can do it like this using Where-Object:

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