Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use wildcards with directories in PowerShell's Get-ChildItem -Exclude cmdlet

For a simple example, let's say I have a folder, Root, with three folders in it; Folder1, Folder2, and Folder3. Each of these folders (including Root) has a bunch of files in them, including .pdb files. I want to use the PowerShell Get-ChildItem cmdlet to return all of the files in all of the folders (including Root), except for the .pdb files in Folder2. If I use:

Get-ChildItem -Path C:\Root -Recurse -Exclude *.pdb

Then I get back all of the non-.pdb files in all of the directories, which is close to what I want. So I assumed that the following would achieve what I want:

Get-ChildItem -Path C:\Root -Recurse -Exclude \*\\Folder2\\*.pdb

But this does not exclude any of the pdb files in Folder2 (or any other folders). I have tried several variants for the -Exclude filter, such as Folder2\\\*.pdb, but I cannot get it to work. In fact, even using \*\\\*.pdb does not seem to do anything; no .pdb files get excluded from any folders.

So it seems that the wildcards cannot be used for directories, only filenames, but I assume I am just doing something wrong. I found this article explaining the wildcard and range operators, but unfortunately it does not discuss using them with directory names; only file names.

like image 769
deadlydog Avatar asked Jan 22 '13 23:01

deadlydog


1 Answers

 gci "C:\Root" -Recurse | Where-Object {$_.FullName -notlike "*Folder2\*.pdb*"} | Export-CSV "C:\Root\Export.csv" -NoType

Tried, tested & one liner :-). This works as I have copied your folder & file structure to replicate. Sorry about it being a few years late, however.

Feel free to tweak the code to your needs, obviously.

like image 59
unkn0wn Avatar answered Sep 21 '22 19:09

unkn0wn