hazjack
hazjack

Reputation: 1715

Delete old files from a big folder with powershell

I have a very big folder (contains subfolders in few levels, millions of files in total). I want to only deletes files that are older than X days (eg 10 days).

My script below works fine for a folder with thousands of files, but is not working for that big folder. Any idea to optimize this? Thanks !

$tmpList = Get-ChildItem -Path $sourceFolder -Recurse
$fileObjects = $tmpList `
        | Where-Object { !$_.PSIsContainer -and ($_.LastWriteTime -le $maxDateToProcess) } `
        | Sort-Object -Property "LastWriteTime" -Descending
$allFiles = $fileObjects | Select -ExpandProperty "FullName"
Remove-Item -Path $allFiles

Upvotes: 1

Views: 131

Answers (1)

JohnnBlade
JohnnBlade

Reputation: 4327

Type the following command to delete files that haven’t been modified in the last 30 days and press Enter:

Get-ChildItem –Path "C:\path\to\folder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item

Upvotes: 1

Related Questions