Last active
August 29, 2015 14:09
-
-
Save bryan-c-oconnell/214f3e6572a998da5e85 to your computer and use it in GitHub Desktop.
bryanoconnell.blogspot.com - Clean up old files using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# |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