Powershell Get-ChildItem Include\Exclude - simple script not working properly

Solution 1:

The -Exclude parameter has never really worked properly. It seems to match on the Name property, which is typically not very useful. You probably just have to do the filtering yourself:

$Include = "*.zip","*.rar","*.tar","*.7zip"
Get-ChildItem "C:\" -Include $Include -Recurse -Force -ErrorAction silentlycontinue | 
    ? { $_.FullName -notmatch "^C:\\Windows" -and $_.FullName -notmatch "^C:\\Program" } |
    Select-Object -ExpandProperty FullName

(By the way, -Filter is much, much faster than -Include. The downside is that you can't give it an array of patterns like you can with -Include. But it still may be faster even if you had to search four times. I couldn't say for sure. It might be worth testing if speed is important to you.)

Solution 2:

I agree with dangph that the -exclude doesn't work as expected.
When using -notmatch you can build a regex pattern with an or |.
This works here with the revised $include:

$Include = @('*.zip','*.rar','*.tar','*.7zip')
$exclude = [RegEx]'^C:\\Windows|^C:\\Program Files'
Get-ChildItem "C:\" -Include $Include -Recurse -Force -EA 0| 
  Where FullName -notmatch $exclude|
  Select-Object -ExpandProperty FullName

EDit Since the excluded folders are first level it is much faster to not iterate them at all, so a two step approach is more efficent:

$Include = @('*.zip','*.rar','*.tar','*.7zip')
$exclude = [RegEx]'^C:\\Windows|^C:\\Program Files'

Get-ChildItem "C:\" -Directory |
  Where FullName -notmatch $exclude|ForEach {
  Get-ChildItem -Path $_.FullName -Include $Include -Recurse -Force -EA 0| 
  Select-Object -ExpandProperty FullName
}