Deleting old files and folders in Powershell

Deleting old files and folders in Powershell

Task is clear from title - we need to delete old files from some directory. There are many cases in life, when you will need to perform such operation. For example - delete old backups.

 

$path = “c:\totalcmd\”; #path for search
$days = 2; #keep files for the last two days
Get-ChildItem -path $path"\*" -include *.zip | ?{$_.creationtime -lt $(Get-Date).adddays($days*-1)} | Remove-Item –Force;

If you need to delete not files but folders, you can add the following parameter: Get-Content -Directory. But such construction will work only in Powershell 3.0 and higher. In Powershell 2.0 that will be more complicated:

$path = “c:\totalcmd\”; #path for search
$days = 2; #оkeep files for the last two days
Get-ChildItem -path $path"\*" | ?{ $_.PSIsContainer -and $_.creationtime -lt $(Get-Date).adddays($days*-1)} | Remove-Item –Force;

 

 

 

script (en), powershell (ru)

  • Hits: 12942
Add comment

Related Articles