This is How to purge the X number days old log file from a directory and it's subdirectory.
@"
===============================================================================
Title: Delete 30 Days old files
Description: Get, Filter, Remove
Requirements: Windows Powershell
Author: Amar Singh
Date: June 01, 2016
===============================================================================
"@
$Now = Get-Date
#----- define amount of days ----#
$Days = "30"
#----- define folder where files are located ----#
$TargetFolder = "C:\inetpub\logs\LogFiles"
#----- define extension ----#
$Extension = "*.log"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)
#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
}
else
{
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}
That's ALL
!!!Cheers!!!
No comments:
Post a Comment