Powershell Script: Delete x days old files from a folder. Days and file types can be changed

## The Script is written by Ali – Spice-IT-up (Spiceworks). It should be used with caution and at your own risk
## ##  I do not take any responsibility. If you accidently tell the script to delete the system files, Contact me so I accidently hit you on the head
## ##  Delete 2 days old files with the extension .log. You can change the number of days and the file type below
## To schedule this script, you will have to run this Script through a batch file with the command: powershell -command “& ‘full:\path\DelOldFiles.ps1’ ”
## If this script help you, please leave some comments and give me some points. I am fairly new at Spiceworks. Thanks

Function GetOldFile
$Days = “2” #You can change the number of days here
$TargetFolder = “G:\PSH” #Enter full Target folder path
if (Test-Path $TargetFolder)
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le “$LastWrite”} #Change the file type to different one if needed (*.log)
foreach ($File in $Files)
{write-host “Deleting file $File” -foregroundcolor “Red”; Remove-Item $File | out-null}
{Write-Host “The folder $TargetFolder doesn’t exist! Check the folder path!” -foregroundcolor “red”}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s