Sep 06 2015

Delete Files Older Than in DOS / Powershell

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 too?
Here are 2 simple scripts that can be run every so often to delete files older than say 30 days for instance in Powershell and DOS.


Remove Files in DOS

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"
)


Delete Files in Powershell

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

$limit = (Get-Date).AddDays(-30)
$path = "C:\Temp"

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

  # Delete any empty directories left behind after deleting 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 command in a schedule task to delete files on a regular basis:

powershell C:\Scripts\ClearFolder.ps1

No responses yet

Trackback URI | Comments RSS

Leave a Reply