Updated->Schedule PowerShell script in windows 2003 to clean any files

I have set up an scheduled task in a windows 2003 that run a PowerShell script, this script runs every week and the purpose is to clean out logs from IIS that otherwise fills the volume.

I used the script from Thomas Maurer to check a folder for files to delete and have customized it after excellent input from Jeffery Hicks, he suggested that i put in parameters instead to make the script more flexible and that way it can be run on any folder in the server with -Path and also set number of days to save -DaysBack, the last parameter has a default value of 30 days:

# Delete all Files in specifed parameter Path 
# and parameter older than 30 day(s) default or
# set by parameter DaysBack
#
# Parameter delyxe Niklas Akerlund / RTS
param(
	[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Path,
	$DaysBack = 30)

$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays(-$Daysback) 

if($Path -ne ""){
	Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
}

I saved it in C:\Scripts\Clean and you must set the execution policy in PowerShell console otherwise you will not be able to run any scripts,

Set-ExecutionPolicy -ExecutionPolicy Remotesigned

then i created the scheduled task, some screen shots follows with the way to set up this, first selesct PowerShell

then select interval that the script is going to be run

I have selected that the script is going to be executed every week at mondays 9 AM

Then set an account and password and click next, the magic comes when going into the advanced properties

As you can see i have added a -File C:\Scripts\Clean\clean.ps1 -Path “C:\windows\system32\LogFiles\W3SVC1” -DaysBack 20 to the PowerShell.exe in the run field, otherwise i will not run any scripts 😉 only the powershell, the -File was also a suggestion from Jeffery Hicks 🙂

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -File c:\Scripts\Clean\clean.ps1 -Path "C:\windows\system32\LogFiles\W3SVC1" -DaysBack 20

Quite simple but so powerful to not have to manually clean folders with logfiles that grows.

If you do not have PowerShell on your windows 2003 you have to install the Windows Management Framework first: kb968929

This script can also of course be run on xp, win7 and win 2008/2008 R2.