Skip to content

Instantly share code, notes, and snippets.

@ilovefreesw
Created December 30, 2022 07:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovefreesw/ac3b85ca9868e92c1acccbbe3e144ff7 to your computer and use it in GitHub Desktop.
Save ilovefreesw/ac3b85ca9868e92c1acccbbe3e144ff7 to your computer and use it in GitHub Desktop.
A PowerShell script to automatically backup Windows Event Logs. Add it to Windows Task Scheduler using the Command Below.
$trigger=New-JobTrigger -Weekly -At "7:00AM" -DaysOfWeek "Monday"
$action="PowerShell.exe -ExecutionPolicy ByPass -File D:\Logs\export-logs.ps1"
$sb=[Scriptblock]::Create($action)
Register-ScheduledJob -Name "Export Logs" -ScriptBlock $sb -Trigger $trigger
# This script exports consolidated and filtered event logs to CSV
# Author: Michael Karsyan, FSPro Labs, eventlogxp.com (c) 2016
#
Set-Variable -Name EventAgeDays -Value 7 #we will take events for the latest 7 days
Set-Variable -Name CompArr -Value @("HOSTNAME") # replace it with your server names
Set-Variable -Name LogNames -Value @("Application", "System") # Checking app and system logs
Set-Variable -Name EventTypes -Value @("Error", "Warning") # Loading only Errors and Warnings
Set-Variable -Name ExportFolder -Value "D:\Logs\backup-logs\"
$el_c = @() #consolidated error log
$now=get-date
$startdate=$now.adddays(-$EventAgeDays)
$ExportFile=$ExportFolder + "el" + $now.ToString("yyyy-MM-dd---hh-mm-ss") + ".csv" # we cannot use standard delimiteds like ":"
foreach($comp in $CompArr)
{
foreach($log in $LogNames)
{
Write-Host Processing $comp\$log
$el = get-eventlog -ComputerName $comp -log $log -After $startdate -EntryType $EventTypes
$el_c += $el #consolidating
}
}
$el_sorted = $el_c | Sort-Object TimeGenerated #sort by time
Write-Host Exporting to $ExportFile
$el_sorted|Select EntryType, TimeGenerated, Source, EventID, MachineName | Export-CSV $ExportFile -NoTypeInfo #EXPORT
Write-Host Done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment