Skip to content
Home / ActioNet Blog / Delete Windows Server Log Files via Powershell Script

Delete Windows Server Log Files via Powershell Script

Written by Nate A.

Windows servers can generate tons of log files on a daily basis.  Managing those log files can be a chore.  Ignoring the log files is not an option, as too many log files could fill up a hard drive.

We recently automated the process of logfile clean up by using a Powershell script that deletes files older than 90 days.  The script was then placed in task scheduler to run nightly.

The script was is a modified version of one found on the internet.  The original source was pretty simple; we stripped it down even further.  There are only 2 variables to set.   Each of the variables is set in the code instead of passing them along via the command line.

The first variable is $days.  Set this to how many files you want to keep.  Ours is -90 for 90 days.

The second is $Path. Set this to the path of the files to delete.  Ours was “C:\inetpub\logs\LogFiles\W3SVC2”  This will vary based upon applications and websites used.

Here is the code:

 

# Module: Powershell script to clean IIS log files

function CleanTempLogfiles()
{
param ($FilePath)
Set-Location $FilePath
Foreach ($File in Get-ChildItem -Path $FilePath)
{
if (!$File.PSIsContainerCopy) 
{
if ($File.LastWriteTime -lt ($(Get-Date).Adddays($days)))

            {
remove-item -path $File -force
Write-Host “Removed logfile: ”  $File
}
}
}
}
$days=-90
$Path=”C:\inetpub\logs\LogFiles\W3SVC2″
Write-Host “Removing IIS-logs keeping last” $days “days”
CleanTempLogfiles($Path)