Zipovanie logov

Stretávam sa s otázkou, čo s automaticky generovanými logmi. Ako zmenšit ich veľkošt prípadne ich zmazať. Našiel som pôsob ako zozipovať súbory, tak som vytvoril tento script.

 

Aplikácia generuje logy v .txt formáte a ukladá ich v adresároch po dňoch.

Tento script:

  • nájde adresáre staršie ako 2 dni
  • zozipuje ich a uloží v adresári Archive
  • povodné adresáre zmaže
$LogsFolderPath = "\\server\C$\Logs"
$Archive = "\\server\C$\Logs\Archive\"
$LogsFolders2days = Get-ChildItem -Directory -Path $LogsFolderPath | Where-Object {$_.CreationTime -lt ((Get-date).AddDays(-2)) -and ($_.CreationTime -gt ((Get-date).AddMonths(-1))) -and ($_.Name -notmatch "Archive")}
$mail = "vy@yourcompany.com"
$log = "\\server\C$\Logs\Archive\Log.txt"

function ZipFiles( $zipfilename, $sourcedir )
                             {
                             Add-Type -Assembly System.IO.Compression.FileSystem
                             $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
                             [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}
$LogsFolders2days | ForEach-Object {
                                                     $SourceDirectory = $_.FullName
                                                     ZipFiles "$LogsFolderPath\Archive\$_.zip" $SourceDirectory
                                                     $ZipFile = Get-ChildItem "$LogsFolderPath\Archive\$_.zip"
                                                     "$((Get-Date).ToString("dd.MM.yyyy")): $($ZipFile.FullName) - $([Math]::round($ZipFile.Length / 1mb,2))MB " | Add-Content $log
 
                                                      Remove-Item $SourceDirectory -Recurse
                                                      }

send-mailmessage -from "Vy <vy@yourcompany.com>" -to $mail -subject "Prebehla komprimacia logov" `
 -BodyAsHtml "Na serveri <b>SERVER</b> boli najdene <b>$($LogsFolders2days.Count)&lt;/b> adresare s logmi starsimi ako 2 dni. Logy boli skomprimovane do adresara Archive a povodne adresare boli zmazane." -Attachments "$log" -smtpServer smtp.yourcompany.com

Author: Martin

Infrastructure engineer | virtualization & cloud enthusiast | vSphere specialist | blogger | VMware vExpert 2017, 2018, 2019, 2020 | VMCE | Slovak VMUG Leader |  user group ambassador for kmug.sk | husband&father

Leave a Reply

Your email address will not be published. Required fields are marked *