Powershell Get-ChildItem Script – Fix Get-ChildItem Include/Exclude Script Issues

powershellps1script

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.

Best Answer

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

Related Question