Author Posts

May 9, 2017 at 6:32 pm

I've been hitting more and more to servers which are filled with IIS logs. I have an export of task which clears over 14 days old files, but I thought there might be a more PS way to do the task 🙂

This is not a tested script yet, but I'll try to find a suitable place to run it tomorrow.

$argument = '-Command "foreach ($folder in (Get-ChildItem -path "C:\inetpub\logs\LogFiles" -directory).FullName) {Get-ChildItem "$folder" *.log | Where-Object {$_.lastwritetime -le (get-date).adddays(-14)} |remove-item}"'
$action   = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $argument
$TaskUserName = New-ScheduledTaskPrincipal -UserID "NT Authority\SYSTEM" -RunLevel Highest -LogonType ServiceAccount
$TaskTrigger  = New-ScheduledTaskTrigger -Daily -At 9pm
$Task = New-ScheduledTask -Action $action -Principal $TaskUserName -Trigger $TaskTrigger -Description "Clears IIS logs older than 14 days" 
Register-ScheduledTask -InputObject $Task -Force -TaskName "IIS Log clearing"

May 10, 2017 at 1:50 pm

Depending on the version of Windows, you could probably use a PSScheduledJob instead of a Scheduled Task, but that's kind of a nitpick, honestly. I'd probably have written this as a command ("Clear-IISLogFiles") and deployed it, in a script module, to the machines. Just a little cleaner-looking that including a mini-script as a command-line argument as you're doing.