Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Scripts to archive Sitecore log files.
Archives old log files int zip format to a separate archive directory.
Michael West
Load the function Compress-Archive. The Get-Item command supports a dynamic parameter
called ID whenever the Path parameter is specified. This basically runs the script first
before continuing.
Execute-Script -Item (Get-Item -ID "{22C47B26-223F-4D5A-B760-9BB3C711AF9E}" -Path master:\)
# The archive filename will closely resemble the format of the default logfile names.
$archiveName = "logs.$([datetime]::Now.ToString("yyyy-MM-dd.HHmmss"))"
$archiveDirectory = "$($SitecoreDataFolder)\archived\"
$logDirectory = "$($SitecoreDataFolder)logs\"
# The filter includes log files older than 14 days based on LastWriteTime.
$filter = {
$date = [datetime]::Today.AddDays(-14)
$_.LastWriteTime -lt $date
# Get all the log files that match the filter criteria. After zipping up remove the log files.
$logs = Get-ChildItem -Path $logDirectory | Where-Object -Filter $filter
if($logs) {
$logs | Compress-Archive -Name $archiveName
$logs | Remove-Item
# The filter includes archive files older than 30 days based on LastWriteTime.
$filter = {
$date = [datetime]::Today.AddDays(-30)
$_.LastWriteTime -lt $date
# Get all the archived files that match the filter criteria. Remove the old archives.
$archives = Get-ChildItem -Path $archiveDirectory | Where-Object -Filter $filter
if($archives) {
$archives | Remove-Item
function Compress-Archive {
[string]$Name = "archive",
begin {
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$level = [System.IO.Compression.CompressionLevel]::Optimal
if($Name -notmatch "zip$") {
$Name += ".zip"
if(!(Test-Path -Path $OutputPath)) {
New-Item -Path $OutputPath -ItemType directory
$zipPath = (Join-Path -Path $OutputPath -ChildPath $Name)
if(Test-Path -Path $zipPath) {
Remove-Item -Path $zipPath
$zipFile = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
process {
if($File) {
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipFile, $File.FullName, $File.Name, $level) | Out-Null
end {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment