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

6

2

Im trying to run the following code as a powershell script,but I cant get it to work. 1st,the following works with one -Include item but I cant seem to get it to work with multiple ones. 2nd, the -Exclude perimeter doesn't seem to work. I still get files from the C:\Windows and C:\Program Files directorys .

$Include = "*.zip","*.rar","*.tar","*.7zip"
$exclude = "C:\Windows","C:\Program Files"
Get-ChildItem "C:\" -Include $Include -Exclude $Exclude -Recurse -Force -ErrorAction silentlycontinue | Select-Object -ExpandProperty FullName

Note: The purpose of this script is to find all compressed files on the system. I know this is probably really simple but I just cant seem to get it to work.

securityghost

Posted 2017-03-20T01:26:54.787

Reputation: 99

Answers

2

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.)

dangph

Posted 2017-03-20T01:26:54.787

Reputation: 3 478

4

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
}

LotPings

Posted 2017-03-20T01:26:54.787

Reputation: 6 150

Once I took out the -Force and the -EA 0 it worked. I don't know why? Thanks. – securityghost – 2017-03-21T02:33:11.850

Sorry for that, PowerShell version differences. Both are supported in higher releases. -EA 0 is just an abreviation for -ErrorAction silentlycontinue – LotPings – 2017-03-21T06:03:30.367