Rama devi
Rama devi

Reputation: 79

How to exclude sub folders

I want to get all "*.exe" files from one folder. It has 3 sub folders. but I want get files from 2 sub folders only. I am trying to use -Exclude in PowerShell. It is working to exclude single file but it is not working to exclude a folder. can anybody tell how to solve it.

This is what I am using the below code it is working to exclude "HWEMNGR.EXE" etc files but Its not allowing me to exclude a sub folder from main folder.

$Files = Get-ChildItem -Path "D:\depot\main" -Recurse -Include "*.exe" -Exclude HWEMNGR.EXE,wmboot.exe,SDClientMobileEdition.exe | % { $_.FullName } 

Thanks

Upvotes: 1

Views: 9652

Answers (2)

Anupam Majhi
Anupam Majhi

Reputation: 124

I will take the following example to explain how I do it:

Get-ChildItem C:\a -include "*.txt" -recurse | %{$_.fullname}

C:\a\b\b1.txt
C:\a\b\b2.txt
C:\a\b\b3.txt
C:\a\c\c1.txt
C:\a\c\c2.txt
C:\a\c\c3.txt
C:\a\d\d1.txt
C:\a\d\d2.txt

Here under C:\a, the subfolders are b,c and d

Now I want *.txt files from b and c to be listed and I want to exclude any file under d subfolder. To achieve this I introduce a where (also used as "?") condition as follows

Get-ChildItem C:\a -include "*.txt" -recurse | ?{$_.fullname -notlike "C:\a\d\*"}  | %{$_.fullname}

C:\a\b\b1.txt
C:\a\b\b2.txt
C:\a\b\b3.txt
C:\a\c\c1.txt
C:\a\c\c2.txt
C:\a\c\c3.txt

I hope this solves your problem.

Upvotes: 0

Matt
Matt

Reputation: 46710

-Exclude is good for file names however it does not have a good track record for folder name\path exclusion. You should use a Where-Object clause to address that.

$Files = Get-ChildItem -Path "D:\depot\main" -Recurse -Include "*.exe" -Exclude "HWEMNGR.EXE","wmboot.exe","SDClientMobileEdition.exe" | 
    Select-Object -ExpandProperty FullName | 
    Where-Object{$_ -notmatch "\\FolderName\\"}

The snippet % { $_.FullName } was replaced by Select-Object -ExpandProperty FullName which does the same thing. Then we use Where-Object to exclude paths where FolderName is not there. It is regex based so we double up on the slashes. This also helps make sure we exclude folders and not a file that might be called "FolderName.exe"

Alternate approach

Like TheMadTechnician points out you could come at this from another direction and just ensure the files come from the only two folders you really care about. Get-ChildItem will take an array for paths so you could also use something like this.

$paths = "D:\depot\main\install","D:\depot\main\debug"
$excludes = "HWEMNGR.EXE","wmboot.exe","SDClientMobileEdition.exe"
$Files = Get-ChildItem $paths -Filter "*.exe" -Exclude $excludes | Select-Object -ExpandProperty FullName

$paths is the only two folders you want results from. You still exclude the files you dont want and then just return the full file paths.

Upvotes: 2

Related Questions