Vikas J
Vikas J

Reputation: 887

PowerShell Script to Delete files from all SubFolders which are older than 30 days

I want to delete all types of Files from below folder structure which is older than 30 Days. So I used below PowerShell Script. But it is not deleting any file.

PowerShell Script:

Get-ChildItem –Path  "C:\Users\VJ\Documents\MainDir" –Recurse | Where-Object { $_.CreationTime –lt (Get-Date).AddDays(-30) } | Remove-Item

Folder Structure:

  MainDir
     |
  SubDir1 -> Folder1 -> Folder2 -> Zip/CSV files 
  SubDir2 -> Folder1->.txt files
               |
              Folder2 -> .txt files

End Result should be all types of Files deleted from all folders - subfolders of MainDir.

Upvotes: 0

Views: 4076

Answers (2)

Theo
Theo

Reputation: 61068

I think you are confusing the properties CreationTime and LastWriteTime.

If you've just copied (old) files to one of the directories in the structure, the CreationTime is the date and time the file was copied there, which can be today. The LastWriteTime property however shows the date and time the file was last written to.

Try:

$refDate = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse -File | 
    Where-Object { $_.LastWriteTime -lt $refDate } | 
    Remove-Item -Force

If you're on PowerShell version less than 3.0, use:

Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse | 
    Where-Object { !$_.PSIsContainer -and  $_.LastWriteTime -lt $refDate } | 
    Remove-Item -Force

Also, check and retype your dashes, because they may LOOK like normal hyphens, in fact they are EN Dashes (Hex value 2013; Decimal 8211)

Hope that helps

Upvotes: 1

Konstantin Baklaev
Konstantin Baklaev

Reputation: 323

Try this:

Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime –lt (Get-Date).AddDays(-30) } | Remove-Item -Force

Upvotes: 0

Related Questions