Delete Old Files and Folders/Directories with Powershell

~ 0 min
2021-01-31 18:37

Use the following powershell script to automate purging of old files (i.e. delete-old.ps1). Simply change the path at top and the desired age to delete.

$limit = (Get-Date).AddDays(-60)
$path = "C:\mydeletepath"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
Average rating 0 (0 Votes)

You cannot comment on this entry