Skip to content

Instantly share code, notes, and snippets.

@macna
Created January 14, 2019 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macna/8621427be32ee0a7531549812e3e2864 to your computer and use it in GitHub Desktop.
Save macna/8621427be32ee0a7531549812e3e2864 to your computer and use it in GitHub Desktop.
A PowerShell script for rotating Apache HTTP Server logs
# Define where Apache writes the log files
$logFiles = "C:\path\to\logs"
# Define the location the log files should be archived to
$logArchive = "C:\path\to\archive"
# Define for how many days we should retain logs in the archive location
$logLimit = (Get-Date).AddDays(-90)
# Stop the Apache HTTP Server service, using a wildcard to find it by name
Get-Service -Name Apache* | Stop-Service
# Datestamp the current log files and move them to the archive location
Get-ChildItem -Path $logFiles -Filter *.log | ForEach-Object {
$newName = "$($_.DirectoryName)\$(Get-Date -Format yyyy-MM-dd)-$($_.BaseName)$($_.Extension)"
Rename-Item -Path $_.FullName -NewName $newName
Move-Item -Path $newName -Destination $logArchive
}
# Start the Apache HTTP Server service, again using a wildcard to find it
Get-Service -Name Apache* | Start-Service
# Delete log files older than the defined number of days
Get-ChildItem -Path $logArchive | Where-Object {$_.CreationTime -lt $logLimit} | Remove-Item -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment