I would like to delete only the files that were created more than 15 days ago in a particular folder. How could I do this using PowerShell?
Powershell – Delete files older than 15 days using PowerShell
powershellpowershell-2.0powershell-3.0
Related Topic
- Windows – How to run a PowerShell script
- Powershell – How to get only directories using Get-ChildItem
- Powershell – What’s the best way to determine the location of the current PowerShell script
- Powershell – How to search a string in multiple files and return the names of files in Powershell
- Powershell – Get full path of the files in PowerShell
- Sql – How Do I create a log using performance monitor in SQL
- Sql-server – Use a calculated column in a where clause
Best Answer
The given answers will only delete files (which admittedly is what is in the title of this post), but here's some code that will first delete all of the files older than 15 days, and then recursively delete any empty directories that may have been left behind. My code also uses the
-Force
option to delete hidden and read-only files as well. Also, I chose to not use aliases as the OP is new to PowerShell and may not understand whatgci
,?
,%
, etc. are.And of course if you want to see what files/folders will be deleted before actually deleting them, you can just add the
-WhatIf
switch to theRemove-Item
cmdlet call at the end of both lines.If you only want to delete files that haven't been updated in 15 days, vs. created 15 days ago, then you can use
$_.LastWriteTime
instead of$_.CreationTime
.The code shown here is PowerShell v2.0 compatible, but I also show this code and the faster PowerShell v3.0 code as handy reusable functions on my blog.