I’m always looking for ways to automate things as much as possible.
One of my current requirements is archiving and deleting old IIS logs on a couple of our Windows 2003 servers. As a result, I ran across this script the other day by Bernie Salvaggio from http://www.berniesalvaggio.com and must say this is another example of a pretty elegant Powershell script.
With only a few changes to the folders and SMTP settings and downloading 7zip, this script worked beautifully.
1: #Windows PowerShell Code###################################################
2: #
3: # NAME: compress-remove-logs.ps1
4: #
5: # AUTHOR: Bernie Salvaggio
6: # EMAIL: BernieSalvaggio(at)gmail(dot)com
7: # TWITTER: @BernieSalvaggio
8: # WEBSITE: http://www.BernieSalvaggio.com/
9: #
10: # COMMENT: Given one or more website directories, parse through the
11: # directory contents to find the previous month's IIS log
12: # files. Zip them up, verify the .zip, and delete the original
13: # log files. The resulting compressed archive will be about
14: # 4.5% of the size of the original log files.
15: #
16: # This script is best utilized by setting a scheduled task
17: # to run it during off-peak times because the compression
18: # process will max out all available cores unless you tell
19: # 7-Zip not to do so (in its own settings, not from this script)
20: #
21: # REQUIRED: 7-Zip is required for this to work. By default this script
22: # looks for the 7-Zip executable, 7za.exe, in C:\7-Zip\
23: #
24: # You have a royalty-free right to use, modify, reproduce, and
25: # distribute this script file in any way you find useful, provided that
26: # you agree that the creator, owner above has no warranty, obligations,
27: # or liability for such use.
28: #
29: ###########################################################################
30:
31: # Build all the pieces for emailing results
32: $ServerName = gc env:computername
33: $SmtpClient = new-object system.net.mail.smtpClient
34: $MailMessage = New-Object system.net.mail.mailmessage
35: # Mail server settings for you to change according to your environment
36: $SmtpClient.Host = "192.168.1.200"
37: $MailMessage.from = ($ServerName + "@mydomain.com")
38: $MailMessage.To.add("yourname@mydomain.com")
39: $MailMessage.Subject = $ServerName + " IIS Log File Archive Results"
40:
41: # The folder(s) you want to back up
42: $TargetPaths = @("C:\TEMP\")
43:
44: # Where you want the backups saved
45: # There's a 1 to 1 relationship between the $BackupsPath and $TargetPaths
46: # For each $TargetPaths you add, you need another $BackupsPath to go along with it
47: $BackupsPath = @("C:\TEMP\")
48:
49: # Short name to append to the filename of the .zip backup file (in case the backup path is the same for multiple target paths)
50: # Each entry here should match the corresponding one in the $TargetPaths array
51: $TargetPathName = @("iis-logs")
52:
53: # Temp file that stores the list of files for 7-Zip to archive
54: $ArchiveList = "c:\temp\listfile.txt"
55:
56: # Temp file used to write the 7-Zip verify results to, then read into the email message body
57: $ArchiveResults = "c:\temp\archive-results.txt"
58: $ArchiveExtension = ".zip"
59:
60: # Just some things to get started...
61: $TargetPathNameCounter = 0
62: $BackupPathCounter=0
63: $CurrentDate = Get-Date
64: $ArchiveDate = $CurrentDate.AddMonths(-1).ToString("MMMyyyy")
65:
66: # Path to the 7-Zip executable
67: $7z = "C:\Program Files\7-Zip\7z.exe"
68:
69: foreach ($TargetPath in $TargetPaths) {
70: # Directory list, minus the folders, where the last write time = the archive date, group the files by month/year
71: dir $TargetPath | where {!$_.PSIsContainer} | where {$_.extension -eq ".log"} | where {"{0:MMM}{0:yyyy}" -f $_.LastWriteTime -eq $ArchiveDate} | group {"{0:MMM}{0:yyyy}" -f $_.LastWriteTime} | foreach {
72:
73: # Generate list of files to compress. For list files, 7-Zip uses UTF-8 encoding by default
74: $_.group | foreach {$_.fullname} | out-file $ArchiveList -encoding utf8
75:
76: # Declare/Cleare the email message body
77: $MailMessage.Body = ""
78:
79: # Create the full name of the zip file we'll create
80: $ZipFileName = $BackupsPath[$BackupPathCounter]+$TargetPathName[$TargetPathNameCounter]+$_.name+$ArchiveExtension
81:
82: # Archive the list of files
83: $null = & $7z a -tzip -mx8 -y $ZipFileName `@$ArchiveList
84:
85: # Check if the operation succeeded
86: if($LASTEXITCODE -eq 0){
87: # If it succeeded, double check with 7-Zip's Test feature
88: $null = & $7z t $ZipFileName | out-file $ArchiveResults
89: if($LASTEXITCODE -eq 0){
90: # Verify success, write out the contents of the verify command to the email message body
91: foreach ($txtLine in Get-Content $ArchiveResults) {$MailMessage.Body += $txtLine + "`n"}
92: # Delete the original files
93: $_.group | Remove-Item
94: } else {
95: $MailMessage.Body = "Error"
96: }
97: } else {
98: $MailMessage.Body = "Error"
99: }
100: $SmtpClient.Send($MailMessage)
101: }
102: Remove-Item $ArchiveList
103: Remove-Item $ArchiveResults
104: $BackupPathCounter++
105: $TargetPathNameCounter++
106: }