Powershell Tip #2 - How to delete older IIS log files from all servers

by rahul 5/27/2012 12:59:14 AM

So you have a lot of IIS Servers to manage and the logs are taking up space? No worries, use/modify the following script and schedule a daily job to delete the older log files automatically every day. This script assumes that you have all the log files in the same location.

#Write down all the server names here. I had only two servers WFE1wSQL and AS1
$Servers = "WFE1wSQL", "AS1"                
#This script assumes that you have the log files in the same folder on all servers.
$source = "C:\WINDOWS\system32\LogFiles"    
$date = Get-Date
#Number of days = 30 would imply deleting all the files older than 30 days.
$retention = $date.AddDays(-30)

foreach ($server in $servers)
{
    try
    {
        Write-host "Deleting the old IIS log files from" $server
        #Make a path like \\ServerName\C$\Windows\System32\Logfiles
        $remotefolder = "\\" + $server + "\" + $source.Replace(":", "$")
        #Use a filter to filter all log files which are older than Retention period
        $folder = Get-Childitem -Path $remotefolder -recurse -filter "ex*.log" | where {$_.CreationTime -le $retention}
        if($folder.Count -gt 0){ $folder | remove-item }
        else {Write-host -ForegroundColor Red "No files found"}
    }
    catch
    {
        $err= $_.Exception;
        Write-Host -ForegroundColor Red $err.Message
    }
}
 

Hope this helps, Wave
Rahul


Quote of the day:
Beauty is in the eye of the beholder and it may be necessary from time to time to give a stupid or misinformed beholder a black eye. - Miss Piggy


blog comments powered by Disqus

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  May 2013  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

All Items
Sign in

Visit Microsoft's Site

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2013, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0