PowerShell: Delete specific files recursively / recursive

Okay, this post I’m going to write down for my personal notes but also for you..
Ever needed to delete a specific file, in my case in need to delete (remove-item) all *.pdb files in one of my Visual Studio Solution.. recursive of course.
To get a list of Files use the Get-ChildItem CmdLet. Extend that command using the –rec or –recurse parameter – so you’ll get all the files recursively, starting from the current path / directory.

Now, we don’t need all the file, but all the files with a specific extension. We’ll use the Where-Object to achieve this. Well if you do Get-ChildItem you’ll get something like:

PS D:\DEMO> Get-ChildItem

    Directory: D:\DEMO

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
d—-        19.02.2010     13:16            DEMO Folder
-a—        19.02.2010     13:17         18 someFile.ext



So, how to get only files with a specific extension? Easy, using Get-Member we can list all properties of Get-ChildItem.

PS D:\DEMO> Get-ChildItem | Get-Member

   TypeName: System.IO.DirectoryInfo

Name                      MemberType     Definition
—-                      ———-     ———-
Mode                      CodeProperty   System.String Mode{get=Mode;}
Create                    Method         System.Void Create(System.Security.AccessControl.DirectorySecurity director…

Extension                 Property       System.String Extension {get;}

FullName                  Property       System.String FullName {get;}



When we want to search for a specific File Type, the Extension Property comes in very handy.

So, to get a list of all, let’s say *.tmp files recursively, we’ll write:

PS D:\DEMO> Get-ChildItem -Rec | Where {$_.Extension -match "tmp"}

    Directory: D:\DEMO

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—        19.02.2010     13:22         12 demo.tmp

    Directory: D:\DEMO\DEMO Folder

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—        19.02.2010     13:22         12 dem32.tmp
-a—        19.02.2010     13:22         12 demo2.tmp



Now, let’s delete all of these *.tmp files using Remove-Item

PS D:\DEMO> Get-ChildItem -Rec | Where {$_.Extension -match "tmp"} | Remove-Item

and they are all gone!