Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / PowerShell

Clean Up Old Files using PowerShell

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
20 Mar 2013CPOL 13.1K   7   1
A simple script for deleting files in bulk

Introduction

I've been working on this blog for just over 6 months now, and my most popular article, by far, is about using PowerShell to extract worksheets from an Excel file. I basically took an old script idea I'd found really useful in a past project, and created a version of it in PowerShell. It was fun to write, and since there's been a lot of interest, I decided to do another one; this time, to help with file cleanup.

Doing a quick Google search (which may be what brought you here) will show you a number of variations on PowerShell scripts for deleting files. I'm sure many of them are perfectly adequate for the task, and in some cases, have features that mine doesn't. My solution excels at code readability and control, the latter of which I feel is fairly important when deleting files in bulk.

Not much else to say about it I guess; the purpose and uses of this script are pretty straightforward.

Here's the code:

# |Info|
# Written by Bryan O'Connell, February 2013
# Purpose: Delete files from a folder haven't been modified for the
# specified number of days.
#
# Sample: DeleteOldFiles.ps1 -folder "C:\test" -days_old 7 [-only_this_type ".xls"]
# 
# Params:
#   -folder: The place to search for old files.
# 
#  -days_old: Age threshold. Any file that hasn't been modified for more than
#  this number of days will be deleted.
# 
#  -only_this_type: This is an optional parameter. Use it to specify that you
#  just want to delete files with a specific file extension. Be sure to 
#  include the '.' with the file extension.
#
# |Info| 

[CmdletBinding()]
Param (
  [Parameter(Mandatory=$true,Position=0)]
  [string]$folder,

  [Parameter(Mandatory=$true,Position=1)]
  [int]$days_old,

  [Parameter(Mandatory=$false,Position=2)]
  [string]$only_this_type
) 

#-----------------------------------------------------------------------------#


# Determines whether or not it's ok to delete the specified file. If no type 
# is specified, all files are ok to delete. If a type IS specified, only files 
# of that type are ok to delete. 

Function TypeOkToDelete($FileToCheck) 
{
  $OkToDelete = $False;

  if ($only_this_type -eq $null) { 
    $OkToDelete = $True; 
  }
  else { 
    if ( ($FileToCheck.Extension) -ieq $only_this_type ) {
      $OkToDelete = $True;
    }
  } 

  return $OkToDelete;
} 

#-----------------------------------------------------------------------------#

$FileList = [IO.Directory]::GetFiles($folder);
$Threshold = (Get-Date).AddDays(-$days_old);

foreach($FileToDelete in $FileList)
{
  $CurrentFile = Get-Item $FileToDelete;
  $WasLastModified = $CurrentFile.LastWriteTime;
  $FileOkToDelete = TypeOkToDelete($CurrentFile);

  if ( ($WasLastModified -lt $Threshold) -and ($FileOkToDelete) )
  {
    $CurrentFile.IsReadOnly = $false;
    Remove-Item $CurrentFile;
    write-Output "Deleted $CurrentFile";
  }
}

write-Output "Press any key to quit ...";
$quit = $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown");

Note: If you run into problems getting the script to run on your machine, there are a few troubleshooting tips in my original article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) SPR Consulting
United States United States
Bryan has been solving business problems with software and Agile methodologies for over twelve years. He has experience in all aspects of the software development lifecycle, having directed multiple projects from client initiation through product delivery, deployment, and growth as a team member, manager or independent contributor. Bryan is also a Certified Scrum Master and Manager.

Comments and Discussions

 
GeneralMy vote of 4 Pin
ApplinxSpec26-Mar-13 3:27
professionalApplinxSpec26-Mar-13 3:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.