Delete files with PowerShell

Delete files with PowerShell

Delete files with PowerShell

How to delete files in a folder older than X amount of days.

$limit = (Get-Date).AddDays(-X)

$path = "C:\example\example"

Remember to replace the X with the desired number of days old files, and change the path to the correct folder.

# Delete files older than the $limit.

$limit = (Get-Date).AddDays(-X)
$path = "C:\example\example"

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.

$limit = (Get-Date).AddDays(-X)
$path = "C:\example\example"

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