Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

Clean Up Old Files using PowerShell

4.00/5 (1 vote)
20 Mar 2013CPOL 13.3K  
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)