Export Windows Logs with Precise Time

1.1k Views Asked by At

I am attempting to export Windows logs using the Get-WinEvent Powershell cmdlet. The following will get me the time precision I am looking for, but this only gets me the timestamp. I need to join the timestamp to other columns that include the machine name, event id, etc.

This code gets me the precise time stamps.

  Get-WinEvent -LogName Application -MaxEvents 10 | Select-Object -Expand TimeCreated | ForEach-Object { 
$date = [DateTime]$_
$date.ToString("yyyy-MM-dd HH:mm:ss")}

The output looks like this which is what I want:

2018-12-06 08:52:28 
2018-12-06 08:52:28 
2018-12-06 08:51:32 
2018-12-06 08:51:31 
2018-12-06 08:51:31 
2018-12-06 08:51:31 
2018-12-06 08:51:31
2018-12-06 08:51:31 
2018-12-06 08:51:31 
2018-12-06 08:44:16

But I need the output to include both the precise time along with things like MachineName, EventID, LevelDisplayName, Message, etc. So in the command below, instead of "TimeCreated", I want to insert the precise time.

Get-WinEvent -LogName Application -MaxEvents 10 | Select-Object TimeCreated,Machinename,Id,LevelDisplayName,Message,Logname | ft

Thanks!

1

There are 1 best solutions below

3
On BEST ANSWER

To have your exact formatting for TimeCreated, use a calculated property

Get-WinEvent -LogName Application -MaxEvents 10 |
   Select-Object @{n='TimeCreated';e={$_.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")}},
                 Machinename,Id,LevelDisplayName,Logname,Message|Format-Table -auto

For more precision you can also include fractions of seconds
(append ,f .. ,fffffff to the format string)

EDIT: I don't have your environment, but write-Host shouldn't be neccessary.

This should output the formatted CreatedTime to the csv

Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-SessionBroker/Operational" `
             -ComputerName $SessionBroker -MaxEvents 150 | 
  Select-Object @{n='TimeCreated';e={$_.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")}}, 
                Machinename,Id,LevelDisplayName,Message,LogName,TaskDisplayName | 
    Export-Csv $RDSLogs\SessionBrokerOperational.csv -Append -NoTypeInformation