PowerShell: Delete specific files recursively / recursive
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
PS D:\DEMO>
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;}
…
…
PS D:\DEMO>
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
PS D:\DEMO>
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!
I finally decided to take a look at Powershell out of necessity at work. I remember a friend telling me years ago that I should try it out. Geez…I wish I had of listened to him then.
Thanks heaps for this – it is saving me a huge amount of time in organizing 100s of GBs of files on our corporate network drive.
How do I save a file, without being able to enter or extract informatioen. On all my files I want to avoid “read only”, and not be able to print my files? I have Office Home and Student 2007. May be I wasn’t suppose to ask a question…but live on disability and can’t afford $38.00 to get a question answered.
Hi Beverlee
i don’t understand you question. can you make it more clear?
/chris
yeah, you really should look into powershell. it’s a mighty tool to organize and manage your systems. especially managing remote systems really rocks!
Based on what you’ve written here, I guess if I want to find all files which have a numeric name larger than say X, then I have to write:
get-childitem | where {$_.name -gt X} | remove-item
Is this right?