How to use directory wildcards in PowerShell Get-ChildItem -Exclude cmdlet

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

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

Then I return all files without .pdb in all directories that are close to what I want. Therefore, I suggested that the following be achieved, 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 tried several options for the -Exclude filter, for example Folder2\\\*.pdb , but I can not get it to work. In fact, even using \*\\\*.pdb does nothing; .pdb files are excluded from any folders.

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

+7
source share
4 answers

I have not seen the exclude option working with directories.

You can try connecting to the Where-Object . I.e

 Get-ChildItem -Recurse *.pdb | Where-Object {$_.FullName -notMatch "folder2"} 
+5
source
  gci "C:\Root" -Recurse | Where-Object {$_.FullName -notlike "*Folder2\*.pdb*"} | Export-CSV "C:\Root\Export.csv" -NoType 

I tried, tested one liner :-). This works since I copied your folder and file structure for replication. Sorry, however, that this was a few years later.

Feel free to customize the code to suit your needs.

+2
source

The answer to OhadH is almost there.

you can use

 Get-ChildItem -Recurse | Where-Object {$_.FullName -notmatch "folder2" -or $_.Name -notlike "*.pdb" } 

or

 Get-ChildItem -Recurse | ? {$_.FullName -notlike "*folder2*" -or $_.Name -notlike "*.pdb" } 

It depends on where your folder2 is located. But I think you have an idea.

I do not like to say this, but PowerShell is not convenient like Bash or other shells.

+1
source

This should work for you:

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

All Articles