Sep 06 2015

DOS / Powershell Scripts to Remove Files Older Than

Published by at 11:09 pm under Windows

System admins face more and more ever-growing directories storing auto-generated reports by scripts or scheduled tasks. Same goes to temp directories and nobody bother cleaning them up. But isn’t it our job?
Here are 2 simple scripts that can be run every so often to delete files older than say 30 days for instance.

The first in DOS is more limited since ForFiles can only deal with the last modified date.

Echo @off
Cls

Set Folder=C:\Reports

if exists %Folder% (
  rem *******************************************
  rem Remove system attributes and cache files
  rem Not processed by the del command
  Forfiles /S /P "%Folder%" /M * /D -30 /C "cmd /c attrib -s -h @path"
  rem Remove files older than 30 days
  Forfiles /S /P "%Folder%" /M * /D -30 /C "cmd /c del /F /Q @path"

  rem Remove empty directories
  for /f "delims=" %%d in ('dir /S /B /AD %SrcDir% ^| sort /R') do rmdir "%%d"
)


Powershell lets you work with the 3 parameters LastAccessTime, LastWriteTime and CreationTime.

$limit = (Get-Date).AddDays(-30)
$path = "Q:\Commun\Echange_Vide_Tous_Les_Mois"

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

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


To run the script, check powershell restrictions with

Get-ExecutionPolicy

If restricted, run

Set-ExecutionPolicy RemoteSigned

And run the following in a schedule task:

powershell C:\Scripts\ClearFolder.ps1

No responses yet

Trackback URI | Comments RSS

Leave a Reply