AD Security logs script
# ============================================================================
# SecurityLogArchive.ps1
# Archives Security*.evtx files older than 30 days
# Creates individual ZIP files
# Deletes original EVTX files after successful archive
# Deletes ZIP files older than 90 days
# Logs all actions
# ============================================================================
$Source = "C:\Windows\System32\winevt\Logs\"
$Destination = "D:\ArchivedSecurityLogs"
$RetentionDays = 30
$LogFile = Join-Path $Destination "SecurityArchive.log"
# Create destination folder if it doesn't exist
if (!(Test-Path $Destination)) {
New-Item -Path $Destination -ItemType Directory -Force | Out-Null
}
Add-Content -Path $LogFile -Value ""
Add-Content -Path $LogFile -Value "================================================================="
Add-Content -Path $LogFile -Value "Archive Job Started : $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Add-Content -Path $LogFile -Value "================================================================="
# Archive Security EVTX files older than 90 days
Get-ChildItem -Path $Source -Filter "Security*.evtx" -File |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) } |
ForEach-Object {
$ZipFile = Join-Path $Destination "$($_.BaseName).zip"
try {
Compress-Archive -Path $_.FullName -DestinationPath $ZipFile -Force
if (Test-Path $ZipFile) {
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | Archived: $($_.FullName) -> $ZipFile"
Remove-Item $_.FullName -Force
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | Deleted EVTX: $($_.FullName)"
}
}
catch {
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | ERROR Archiving $($_.Name) : $($_.Exception.Message)"
}
}
# Delete ZIP files older than 90 days
Get-ChildItem -Path $Destination -Filter "*.zip" -File |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) } |
ForEach-Object {
try {
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | Deleted Old ZIP: $($_.FullName)"
Remove-Item $_.FullName -Force
}
catch {
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | ERROR Deleting ZIP $($_.Name) : $($_.Exception.Message)"
}
}
Add-Content -Path $LogFile -Value "Archive Job Completed : $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Add-Content -Path $LogFile -Value "================================================================="
Comments
Post a Comment