PI Services

Le blog des collaborateurs de PI Services

Script Powershell - Archive log files to Zip

Le script ci-dessous archive des fichiers de log plus ancien que $daysthreshold vers une archive zip existante ($zipfilepath). Il crée le sous dossier et l'archive zip horodatée si elle n'existe pas.

ArchiveLogToZip.ps1

 

###############################################################
### ArchiveLogs.ps1                                    ###
### Add Log Files older than $days to existing zip archive. ###

### Params
### $logpath: Log Folder
### $archpath: Archive Folder
### $zipfilePath: zip file path
### $daysthreshold: Treat log older than $daysthreshold days
###############################################################
 
Param(
$logpath = "C:\MyLogFolder", 
$archpath = "C:\MyLogFolder\Archive\",
$zipfilePath =  "$archpath"+"*.zip",
[int]$daysthreshold = 0 
)
 



# Test if $archpath exist
If ( -not (Test-Path $archpath)) {New-Item $archpath -type directory} 
 
# Get items to archive
$ItemsToArc = Get-Childitem -Path $logpath -recurse | Where-Object {$_.extension -eq ".log" -and $_.LastWriteTime -lt (get-date).AddDays(-$daysthreshold)}

# Log and exit if  No items to archive
If (! $ItemsToArc)
    {
    Write-Host -F Yellow "No items to archive - Check the existence of the logs"
    exit 0
    }



# If the zip file not exist, create it
if (!(Get-Item $zipfile -ErrorAction SilentlyContinue))
{
$date = $(Get-Date).ToString("MM-dd-yyyy_HH-mm-ss")
New-Item -Path "$archpath$date.zip"
$zipfile = $(Get-Item "$archpath$date.zip").FullName
}
Else
{
$zipfile = $(Get-Item $zipfilePath).FullName
}


# Create a com object that will represent the zip file
$Zip = New-Object -ComObject Shell.Application

write-progress -activity "Archiving Data" -status "Progress..." 

try
{
$ItemsToArc | foreach {$Zip.namespace($zipfile).Movehere($_.fullname,8) ; start-sleep -Seconds 3}
}
catch
{
Write-Host "Error during File add to Zip"
}

 

Ajouter un commentaire

Loading