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

deadlydog picture deadlydog · Jan 23, 2013 · Viewed 33.2k times · Source

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.

Answer

Paul Rowland picture Paul Rowland · Jan 23, 2013

I haven't seen the exclude parameter working with directories either.

You could try piping into Where-Object. That is,

Get-ChildItem -Recurse *.pdb | Where-Object {$_.FullName -notMatch "folder2"}