Export Windows event log and send report to IT administrators

Introduction

This script can be used to export specified Windows event log to CSV file. Then will send email to specified IT administrators with this attachment.

Scenarios

IT Administrators may want to know whether some specific events occurred on their servers. Sometimes they also need to collect some event log for daily reports. 

Script

This script contains only one function, Export-OSCEvent. You can use this script in following ways:

1. Download the script.

2. Open the script file with Notepad or any other script editors.

3. Scroll down to the end of the script file, and then add the example command that you want to run.

4. Save the file then run the script via powershell in “Run as administrator” mode.

Tips: You can run this script manually or by scheduler task.

How to create a scheduler task:

1. Open “Task Scheduler” from control panel.

2. Click “Create task”

3. Pick a name, and choose “Run whether user is logged on or not”
 

4. Choose “Triggers” Tab, Click “New”

5. Specify the option you like, then Click “OK” to create a trigger

6. Choose “Actions” tab, Click “New”

7. Copy the following command to “Program/script” textbox, click “OK”

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". C:\ ExportEvent.ps1"

 

8.       Click “OK”. Till now task has been created.

Examples 

Example 01How to displays help about the Export-OSCEvent function

To display help about the Export-OSCEvent  function, run the following command:

Get-Help Export-OSCEvent -Full 
 

Example 02How to export windows event log, and send report to administrator

To export event log with event ID 4634 and 4624, send report to administrator@test2012.com and david@test2012.com, run the following command:

Export-OSCEvent -Path "C:\Eventlog.csv" -EventID 4634,4624 -SmtpServer "Ex01" -Subject "Eventlog daily check" -From "administrator@test2012.com" –To "administrator@test2012.com","david@test2012.com"

 

CSV file appears as below:

 

Email appears as below:

Here are some code snippets for your reference. To get the complete script sample, please click the download button at the beginning of this page.

PowerShell
Edit|Remove
#export a certain eventlog with specified log name and event ID for last 24 hours.  
Get-WinEvent -LogName $LogName -MaxEvents 1000 -EA SilentlyContinue | Where-Object {$_.id -in $EventID -and $_.Timecreated -gt (Get-date).AddHours(-24)} | Sort TimeCreated -Descending | Export-Csv $Path -NoTypeInformation 
 

Additional Resources

Technical Resources:

Windows PowerShell Advanced Function
http://technet.microsoft.com/en-us/library/dd315326.aspx

Export-CSV
http://technet.microsoft.com/en-us/library/hh849932

Send-MailMessage
http://technet.microsoft.com/en-us/library/hh849925

Get-WinEvent
http://technet.microsoft.com/en-us/library/hh849682.aspx