How to exclude list of items from Get-ChildItem result in powershell?
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
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) }
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.