Mittwoch, 16. Dezember 2009

Delete Files older then X Days Powershell

1. set-executionpolicy RemoteSigned
2. within a batch -> powershell -command "& 'SCRIPTNAME.ps1' " for Scheduled Task.



Function GetOldFile
{
$Days = "2"
$TargetFolder = "C:\pathtofolder"
if (Test-Path $TargetFolder)
{
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{write-host "Deleting file $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
}
Else
{Write-Host "Folder $TargetFolder doesnt exist! Recheck the folder path!"}
}
GetOldFile

Keine Kommentare: