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