Last active
August 29, 2015 14:16
-
-
Save mortenya/5eda2bdd88eb8b166ae5 to your computer and use it in GitHub Desktop.
From a few examples on StackOverflow I put together this POC script for backing up and zipping Windows Security Logs to save them for compliance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Function to zip the archived log, requires .NET 4.5 | |
| function zipFiles($sourceDir, $zipFileName) | |
| { | |
| Add-Type -Assembly System.IO.Compression.FileSystem | |
| $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal | |
| [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $zipFileName, $compressionLevel, $false) | |
| } | |
| # Function to zip the archived log, requires 7zip (has command line version) | |
| function create-7zip([String] $sourceDir, [String] $zipFileName) | |
| { | |
| [string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe"; | |
| [Array]$arguments = "a", "-tzip", "$zipFileName", "$sourceDir", "-r"; | |
| & $pathToZipExe $arguments; | |
| } | |
| # Get the Security Event Log into an Object | |
| $sEvents = Get-WmiObject -Class Win32_NTEventlogFile | where { $_.LogfileName -eq 'Security' } | |
| # Test for Backup directory, create it if it doesn't exist | |
| $backupDir = "C:\evt-backup\{0}_Security_{1:MM-dd-yyyy}"-f $env:COMPUTERNAME,[datetime]::Now | |
| if (-not (Test-Path $backupDir)) | |
| { | |
| New-Item -Path $backupDir -ItemType Directory | Out-Null | |
| } | |
| # Build the Backup file name | |
| $file = "{0}_Security_{1:MM-dd-yyyy}.evt" -f $env:COMPUTERNAME,[datetime]::Now | |
| # Full path for log backup | |
| $path = "$backupDir\$file" | |
| # Arguements for zip file creation | |
| $zipFileName = "$backupDir.zip" | |
| $sourceDir = "$backupDir" | |
| # Do the Backup and capture the returnvalue to chek for errors | |
| $errBackup = ($sEvents.BackupEventlog($path)).ReturnValue | |
| # If the backup is successfull, clear the log and verify ReturnValue for success | |
| if ($errBackup -eq 0) | |
| { | |
| Write-Verbose "Security log successfully archived" | |
| <# | |
| $errClear = ($sEvents.ClearEventlog()).ReturnValue | |
| if ($errClear -eq 0) { | |
| Write-Verbose "Security log successfully cleared" | |
| } | |
| #> | |
| } | |
| else | |
| { | |
| Write-Verbose "Backup failed with return code $errBackup" | |
| } | |
| #zipFiles $sourceDir $zipFileName | |
| #create-7zip $sourceDir $zipFileName |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment