Running a Powershell to script delete folders older then 7 days through Scheduled Tasks

Powershell

Hi today’s blog is about how to automate recurring task like cleaning up in files and folder. Earlier I used a VB- or bat script, but this days are over. Now it’s time for Powershell! 🙂

My job was to delete all old backup files and folder older then 10 days except two folders “Import” and “Export”. So I did a research and found some nice coding on Technet and modified and tested it to my need and used Scheduled Tasks to execute it.

My script – CleanUp.ps1:
# Specify days
$days = (get-date).addDays(-10)

# specify path to root folder
$path = “F:\Filemaker Backup”

#exclude folders by name
$exclude1 = “Exports”
$exclude2 = “Imports”

# format date
$date = get-date -format d

# replace \ by –
$date = $date.ToString().Replace(“/”, “-“)
$a= Get-ChildItem $path | Where{$_.LastWriteTime -lt $days }
$a | foreach-object{

# expand the condtion if more folders needs to be excluded
if (($_ -notlike $exclude1) -and ($_ -notlike $exclude2))
{
$b = $_
write-host $b
}
$b | Foreach-Object { del $_.FullName -recurse}
}

Created a Scheduled Taks and used the command:
powershell.exe -command &{Set-ExecutionPolicy Unrestricted; “C:\Backup\CleanUp.ps1”}
Start in: C:\Backup

For more help and guides take a look at Technet:
Owner’s Manual

Leave a Reply