Written by 1:08 pm Microsoft, PowerShell, Windows, Windows Server • 28 Comments

PowerShell: Delete Files older than

PowerShell Delete Files older than

This is a simple PowerShell script which deletes Files older than some days. You can use it to cleanup old logfiles or other things. If you run the script the first time you can add the “-WhatIf” parameter after Remove-Item command. This example will use PowerShell to delete files older than 30 days.

# Delete all Files in C:\temp older than 30 day(s)
$Path = "C:\temp"
$Daysback = "-30"
 
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

If you need to delete files in subfolders too, you can use this script. This is the same script with the Get-Childitem parameter “-Recurse”.

# Delete all Files in C:\temp older than 30 day(s)
$Path = "C:\temp"
$Daysback = "-30"
 
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse ( | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

I hope this helps you and gives you a quick PowerShell code snipped to remove files older than a specific date using PowerShell. Also check out my PowerShell snipped to copy logfiles with date and content.

Tags: , , , , , , , , , , , Last modified: June 15, 2020
Close Search Window
Close