Last active
August 29, 2015 14:16
-
-
Save chelnak/27f899b9292dac485fa3 to your computer and use it in GitHub Desktop.
Delete IIS logs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Clean-Logs { | |
<# | |
.SYNOPSIS | |
Remove files oder than x days from x location | |
.DESCRIPTION | |
Mainly used to remove IIS logs that are older than a certain number of days. | |
.EXAMPLE | |
Clean-Logs -Retention 7 -Directory D:\Logs | |
.PARAMETER Retention | |
Number of days to retain logs. Specifying 7 will remove logs older than 7 days. | |
.PARAMETER Directory | |
The path to the target log directory. The cmdlet will default to C:\inetpub\logs\LogFiles. | |
#> | |
[CmdletBinding()] | |
param | |
( | |
[Parameter(Mandatory=$True, | |
HelpMessage='Specify your desired retention period and log location')] | |
[int]$Retention, | |
[string]$Directory = 'C:\inetpub\logs\LogFiles', | |
[switch]$ShowOnly | |
) | |
begin { | |
$now = Get-Date | |
$extension = "*.log" | |
$lastWrite = $Now.AddDays(-$retention) | |
$files = Get-ChildItem $Directory -Include $extension -Recurse | ? {$_.LastWriteTime -le $lastWrite} | |
Write-Verbose -Message " - Current time: $now" | |
Write-Verbose -Message " - Last write time: $lastWrite" | |
Write-Verbose -Message " - Retention days: $Retention" | |
Write-Verbose -Message " - File extension: $extension" | |
Write-Verbose -Message " - Number of files $($files.count)" | |
} | |
process { | |
if (!$ShowOnly){ | |
$files | ForEach-Object { | |
if ($_ -ne $NULL) { | |
Remove-Item $_.FullName | Out-Null | |
} | |
} | |
} | |
} | |
end{} | |
} | |
#Run from a scheduled task with %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noprofile D:\Scripts\Delete-IISLogs.ps1 | |
#Remove -ShowOnly to delete logs | |
Clean-Logs -Retention 7 -Directory 'C:\inetpub\logs\LogFiles' -ShowOnly -Verbose |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment