Skip to content

Instantly share code, notes, and snippets.

@bryan-c-oconnell
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryan-c-oconnell/214f3e6572a998da5e85 to your computer and use it in GitHub Desktop.
Save bryan-c-oconnell/214f3e6572a998da5e85 to your computer and use it in GitHub Desktop.
bryanoconnell.blogspot.com - Clean up old files using PowerShell
# |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");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment