Luis Diaz
asked on
Batch or VBscript: export log events into a csv file
Hello experts,
I was wondering if there is a way to export export logs through cmd / batch / vbscript based on the task id of the specific event?
Thank you gain for your help.
I was wondering if there is a way to export export logs through cmd / batch / vbscript based on the task id of the specific event?
Thank you gain for your help.
What logs are you referring to, a particular windows event log (and if so which one), or some other log?
~bp
~bp
ASKER
The Microsoft Log parser tool provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory.
Download
https://www.microsoft.com/en-us/download/details.aspx?id=24659
Note: it installs PARSER.EXE into the "C:\Program Files (x86)\Log Parser 2.2" folder
Example command line usage
https://mlichtenberg.wordpress.com/2011/02/03/log-parser-rocks-more-than-50-examples/
Hopefully this helps
Download
https://www.microsoft.com/en-us/download/details.aspx?id=24659
Note: it installs PARSER.EXE into the "C:\Program Files (x86)\Log Parser 2.2" folder
Example command line usage
https://mlichtenberg.wordpress.com/2011/02/03/log-parser-rocks-more-than-50-examples/
Hopefully this helps
This will output last 20 system event logs in eventlog.txt.
You can try this:
WEVTUtil query-events System /count:20 /rd:true /format:text > eventlog.txt
Change System to Application, Security or Setup depending on what you need.
You can save this (or any other similar) command to a .bat file and schedule it on start-up
Hope this helps :)
You can try this:
WEVTUtil query-events System /count:20 /rd:true /format:text > eventlog.txt
Change System to Application, Security or Setup depending on what you need.
You can save this (or any other similar) command to a .bat file and schedule it on start-up
Hope this helps :)
Like i said. Powershell :)
Get-EventLog -LogName System | Where-Object {$_.EventID -eq 6008} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\it\event.csv"
ASKER
You need to use the whole line of code:
It looks like you started on 'Where-Object', start on 'Get-EventLog'. Otherwise, there is no object to ask 'where'.
Get-EventLog -LogName System | Where-Object {$_.EventID -eq 6008} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\it\event.csv"
It looks like you started on 'Where-Object', start on 'Get-EventLog'. Otherwise, there is no object to ask 'where'.
ASKER
Thank you it works:
I have few remarks:
How can I do to:
1-Add another event log id, the idea is to report the following Id's reported: 6008,6005,6006,1074
2-report automatically the computer name in the title of the csv file.
Thank you again for your help.
I have few remarks:
How can I do to:
1-Add another event log id, the idea is to report the following Id's reported: 6008,6005,6006,1074
2-report automatically the computer name in the title of the csv file.
Thank you again for your help.
$eventIds = 6008,6005,6006,1074
foreach ($event in $eventIds)
{
Get-EventLog -LogName System | Where-Object {$_.EventID -eq $event} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\it\$env:computername.csv" -Append -noTypeInformation
}
Just edit $eventIds with the events you want to use.
(If this is the accepted solution, be sure to share points with Benjamin Volgar).
ASKER
Of course:
I have just a remark to add. I have to lunch this script in 20 VM's however it will be time consuming to contect into them and perform the analysis.
Do you think there is a way to generate individually an event log file for each VM, from my local machine (I am declared as administrator in the various VM's) and directly report the various VM in the script?
Thank you again for your help.
I have just a remark to add. I have to lunch this script in 20 VM's however it will be time consuming to contect into them and perform the analysis.
Do you think there is a way to generate individually an event log file for each VM, from my local machine (I am declared as administrator in the various VM's) and directly report the various VM in the script?
Thank you again for your help.
Something like this should work:
$eventIds = 6008,6005,6006,1074
$computers = "computer1","computer2","computer3"
foreach ($computer in $computers)
{
foreach ($event in $eventIds)
{
Get-EventLog -ComputerName $computer -LogName System | Where-Object {$_.EventID -eq $event} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\test\$computer.csv" -Append -noTypeInformation
}
}
ASKER
I changed the output folder to c:\test which is what I use on my system. Here's the original path added back in.
$eventIds = 6008,6005,6006,1074
$computers = "computer1","computer2","computer3"
foreach ($computer in $computers)
{
foreach ($event in $eventIds)
{
Get-EventLog -ComputerName $computer -LogName System | Where-Object {$_.EventID -eq $event} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\it\$computer.csv" -Append -noTypeInformation
}
}
ASKER
Ok, I relaunch from a VM the previous script and it works:
Concerning the formating of the file. How can I get a ";" delimiter in order to have information reported in multiple columns.
I wasn't able to find where is the reported eventid in the select in order to have for the each line the event id relatd.
Thank you again for your help.
Concerning the formating of the file. How can I get a ";" delimiter in order to have information reported in multiple columns.
I wasn't able to find where is the reported eventid in the select in order to have for the each line the event id relatd.
Thank you again for your help.
ASKER
@Bill: Concerning the vbscript approach I found the following code :
https://social.technet.microsoft.com/Forums/scriptcenter/en-US/28c7d7bc-29da-485c-9ca0-b23f2d42205c/vbscript-extract-data-from-windows-event-log?forum=ITCG
I wasn't not able to export the csv file as I don't why should I set up the order to call the various reported functions.
Thank you again for your help.
---------------
'Script Name : QueryEventLogs.vbs
'Author : Matthew Beattie
'Created : 16/09/09
'Description : This script queries the event log for...whatever you want it to! Just set the event log name and event ID's!
'----------------------------------------------------------------------------------------------------------------------------
'Initialization Section
'----------------------------------------------------------------------------------------------------------------------------
Option Explicit
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim objDictionary, objFSO, wshShell, wshNetwork
Dim scriptBaseName, scriptPath, scriptLogPath
Dim ipAddress, macAddress, item, messageType, message
On Error Resume Next
Set objDictionary = NewDictionary
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = CreateObject("Wscript.Shell")
Set wshNetwork = CreateObject("Wscript.Network")
scriptBaseName = objFSO.GetBaseName(Wscript.ScriptFullName)
scriptPath = objFSO.GetFile(Wscript.ScriptFullName).ParentFolder.Path
scriptLogPath = scriptPath & "\" & IsoDateString(Now)
If Err.Number <> 0 Then
Wscript.Quit
End If
On Error Goto 0
'----------------------------------------------------------------------------------------------------------------------------
'Main Processing Section
'----------------------------------------------------------------------------------------------------------------------------
On Error Resume Next
PromptScriptStart
ProcessScript
If Err.Number <> 0 Then
MsgBox BuildError("Processing Script"), vbCritical, scriptBaseName
Wscript.Quit
End If
PromptScriptEnd
On Error Goto 0
'----------------------------------------------------------------------------------------------------------------------------
'Functions Processing Section
'----------------------------------------------------------------------------------------------------------------------------
'Name : ProcessScript -> Primary Function that controls all other script processing.
'Parameters : None ->
'Return : None ->
'----------------------------------------------------------------------------------------------------------------------------
Function ProcessScript
Dim events, hostName, logName, eventNumbers, startDateTime, endDateTime, i
hostName = wshNetwork.ComputerName
logName = "System"
eventNumbers = Array("29","17")
startDateTime = DateAdd("n", -120, Now)
'-------------------------------------------------------------------------------------------------------------------------
'Construct part of the WMI Query to account for searching multiple eventID's
'-------------------------------------------------------------------------------------------------------------------------
If Not QueryEventLog(events, hostName, logName, eventNumbers, startDateTime) Then
Exit Function
End If
'-------------------------------------------------------------------------------------------------------------------------
'Log the scripts results to the scripts
'-------------------------------------------------------------------------------------------------------------------------
LogMessage "Event Code,Date Time Written"
For i = 0 To UBound(events)
LogMessage events(i)
Next
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : QueryEventLog -> Primary Function that controls all other script processing.
'Parameters : results -> Input/Output : Variable assigned to an array of results from querying the event log.
' : hostName -> String containing the hostName of the system to query the event log on.
' : logName -> String containing the name of the Event Log to query on the system.
' : eventNumbers -> Array containing the EventID's (eventCode) to search for within the event log.
' : startDateTime -> Date\Time containing the date to finish searching at.
' : minutes -> Integer containing the number of minutes to subtract from the startDate to begin the search.
'Return : QueryEventLog -> Returns True if the event log was successfully queried otherwise returns False.
'----------------------------------------------------------------------------------------------------------------------------
Function QueryEventLog(results, hostName, logName, eventNumbers, startDateTime)
Dim wmi, query, result, eventsDict, eventInfo
Dim wmiDateTime, errorCount, i
QueryEventLog = False
errorCount = 0
If Not IsArray(eventNumbers) Then
eventNumbers = Array(eventNumbers)
End If
'-------------------------------------------------------------------------------------------------------------------------
'Construct part of the WMI Query to account for searching multiple eventID's
'-------------------------------------------------------------------------------------------------------------------------
query = "Select * from Win32_NTLogEvent Where Logfile = " & SQ(logName) & " And (EventCode = "
For i = 0 To UBound(eventNumbers)
query = query & SQ(eventNumbers(i)) & " Or EventCode = "
Next
On Error Resume Next
Set eventsDict = NewDictionary
If Err.Number <> 0 Then
LogError "Creating Dictionary Object"
Exit Function
End If
Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate,(Security)}!\\" & hostName & "\root\cimv2")
If Err.Number <> 0 Then
LogError "Creating WMI Object to connect to " & DQ(hostName)
Exit Function
End If
'----------------------------------------------------------------------------------------------------------------------
'Create the "SWbemDateTime" Object for converting WMI Date formats. Supported in Windows Server 2003 & Windows XP.
'----------------------------------------------------------------------------------------------------------------------
Set wmiDateTime = CreateObject("WbemScripting.SWbemDateTime")
If Err.Number <> 0 Then
LogError "Creating " & DQ("WbemScripting.SWbemDateTime") & " object"
Exit Function
End If
'----------------------------------------------------------------------------------------------------------------------
'Build the WQL query and execute it.
'----------------------------------------------------------------------------------------------------------------------
wmiDateTime.SetVarDate startDateTime, True
query = Left(query, InStrRev(query, "'")) & ") And (TimeWritten >= " & SQ(wmiDateTime.Value) & ")"
Set results = wmi.ExecQuery(query)
If Err.Number <> 0 Then
LogError "Executing WMI Query " & DQ(query)
Exit Function
End If
For Each result In results
Do
eventInfo = ""
wmiDateTime.Value = result.TimeWritten
eventInfo = eventInfo & result.EventCode & ","
eventInfo = eventInfo & wmiDateTime.GetVarDate & ","
If Err.Number <> 0 Then
LogError "Enumerating Event Properties from the " & DQ(logName) & " event log on " & DQ(hostName)
errorCount = errorCount + 1
Err.Clear
Exit Do
End If
'----------------------------------------------------------------------------------------------------------------
'Remove the ending comma from the event information string and add it to the dictionary if it doesn't exist.
'----------------------------------------------------------------------------------------------------------------
eventInfo = Left(eventInfo, Len(eventInfo) - 1)
If Not eventsDict.Exists(eventInfo) Then
eventsDict(eventsDict.Count) = eventInfo
End If
Loop Until True
Next
On Error Goto 0
If errorCount <> 0 Then
Exit Function
End If
results = eventsDict.Items
QueryEventLog = True
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : NewDictionary -> Creates a new dictionary object.
'Parameters : None ->
'Return : NewDictionary -> Returns a dictionary object.
'----------------------------------------------------------------------------------------------------------------------------
Function NewDictionary
Dim dict
Set dict = CreateObject("scripting.Dictionary")
dict.CompareMode = vbTextCompare
Set NewDictionary = dict
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : SQ -> Places single quotes around a string
'Parameters : stringValue -> String containing the value to place single quotes around
'Return : SQ -> Returns a single quoted string
'----------------------------------------------------------------------------------------------------------------------------
Function SQ(ByVal stringValue)
If VarType(stringValue) = vbString Then
SQ = "'" & stringValue & "'"
End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : DQ -> Place double quotes around a string and replace double quotes
' : -> within the string with pairs of double quotes.
'Parameters : stringValue -> String value to be double quoted
'Return : DQ -> Double quoted string.
'----------------------------------------------------------------------------------------------------------------------------
Function DQ (ByVal stringValue)
If stringValue <> "" Then
DQ = """" & Replace (stringValue, """", """""") & """"
Else
DQ = """"""
End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue -> Input date/time value.
'Return : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateString(dateValue)
If IsDate(dateValue) Then
IsoDateString = Right ("000" & Year(dateValue), 4) & "-" & _
Right ( "0" & Month(dateValue), 2) & "-" & _
Right ( "0" & Day(dateValue), 2)
Else
IsoDateString = "0000-00-00"
End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : LogMessage -> Parses a message to the log file.
'Parameters: message -> String containnig the message to include in the log file.
'Return : None ->
'----------------------------------------------------------------------------------------------------------------------------
Function LogMessage(message)
If Not LogToFile(scriptLogPath & ".log", message) Then
Exit Function
End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : LogError -> Logs the current information about the error object.
'Parameters: message -> String containnig the message that relates to the process that caused the error.
'Return : None ->
'----------------------------------------------------------------------------------------------------------------------------
Function LogError(message)
Dim errorMessage
errorMessage = "Error " & Err.Number & " (Hex " & Hex(Err.Number) & ") " & message & ". " & Err.Description
If Not LogToFile(scriptLogPath & ".err", errorMessage) Then
Exit Function
End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : LogToFile -> Write a message into the user's network log file.
'Parameters : LogSpec -> String containing the Folder path, file name and extension of the log file to write to.
' : message -> String containing the Message to be logged.
'Return : LogToFile -> Returns True if successful otherwise returns false.
'----------------------------------------------------------------------------------------------------------------------------
Function LogToFile(logSpec, message)
LogToFile = False
On Error Resume Next
With objFSO.OpenTextFile(logSpec, ForAppending, True)
.WriteLine message
.Close
End With
If Err.Number <> 0 Then
Exit Function
End If
On Error Goto 0
LogToFile = True
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : BuildError -> Builds a string of information relating to the error object.
'Parameters: message -> String containnig the message that relates to the process that caused the error.
'Return : BuildError -> Returns a string relating to error object.
'----------------------------------------------------------------------------------------------------------------------------
Function BuildError(message)
BuildError = "Error " & Err.Number & " (Hex " & Hex(Err.Number) & ") " & message & ". " & Err.Description
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : PromptScriptStart -> Prompt when script starts.
'Parameters : None
'Return : None
'----------------------------------------------------------------------------------------------------------------------------
Function PromptScriptStart
MsgBox "Now processing the " & DQ(Wscript.ScriptName) & " script.", vbInformation, scriptBaseName
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name : PromptScriptEnd -> Prompt when script has completed.
'Parameters : None
'Return : None
'----------------------------------------------------------------------------------------------------------------------------
Function PromptScriptEnd
MsgBox "The " & DQ(Wscript.ScriptName) & " script has completed successfully.", vbInformation, scriptBaseName
End Function
'----------------------------------------------------------------------------------------------------------------------------
reported at:https://social.technet.microsoft.com/Forums/scriptcenter/en-US/28c7d7bc-29da-485c-9ca0-b23f2d42205c/vbscript-extract-data-from-windows-event-log?forum=ITCG
I wasn't not able to export the csv file as I don't why should I set up the order to call the various reported functions.
Thank you again for your help.
Seems like the powershell approach is way more simple that the VBS, I would stick with that, feels like you are almost there.
You can change the delimiter on the Export-Csv command by adding -Delimiter ";", something like:
(no points for this post please, others have done the work for the powershell approach...)
You can change the delimiter on the Export-Csv command by adding -Delimiter ";", something like:
Get-EventLog -ComputerName $computer -LogName System | Where-Object {$_.EventID -eq $event} |select TimeGenerated,entrytype,instanceid,message | Export-Csv "c:\it\$computer.csv" -Delimiter ";" -Append -noTypeInformation
~bp(no points for this post please, others have done the work for the powershell approach...)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
It works, thank you very much for your help.
Open in new window
and export:
Open in new window