Friday, May 10, 2013

Clean up old files using PowerShell


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.

No comments:

Post a Comment