如何使用Eventlog和查询?

时间:2016-01-31 01:38:26

标签: powershell-v3.0 event-log

我正在尝试使用ExportLog()来获取指定的日期事件日志。以下代码工作正常:

$Filter = "*[System[TimeCreated[@SystemTime>='2016-01-29T15:00:00.000Z' and @SystemTime<='22016-01-30T14:59:59.999Z']]]"
for ( $i = 0 ;$i -lt  $LogName.count; $i++ ) {
    $OutFileName = $LogName[$i] + "_" + $LogDate + ".evtx"
    $OutFolders  = $OutFolder + "\" + $LogName[$i]
    $OutFile     = $OutFolders + "\" + $OutFileName

    Write-Output $OutFile

    if ((Test-Path $OutFolders) -eq $false){
        New-Item -Path $OutFolders -Type directory
    }
    if ((Test-Path $OutFile) -eq $true){
        Remove-Item $OutFile
    }

    $evsession = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogSession
    $evsession.ExportLog($LogName[$i], "LogName", $Filter, $OutFile)

但这并没有像我预期的那样奏效:

$LogDate   = (Get-Date).AddDays($fromDay).ToString("yyyyMMdd")
$StartTime =
  [DateTime] (Get-Date).AddDays($fromDay).ToString("yyyy/MM/dd 00:00:00")

$EndUtcTime1   
  [DateTime] (Get-Date).AddDays($fromDay).ToString("yyyy/MM/dd 23:59:59")

$Filter = "*[System[TimeCreated[@SystemTime>= '$StartTime' and @SystemTime<= '$EndUtcTime' ]]]"

# after this it's the same as the above code snippet

有没有人知道它无法正常工作的原因?

1 个答案:

答案 0 :(得分:0)

您的第二个代码示例无法正常工作,因为它错误地格式化了时间戳。事件日志中的时间戳使用格式yyyy-MM-ddTHH:mm:ss.fffK,而您使用格式yyyy/MM/dd HH:mm:ss

将日期计算更改为:

$fmtTimestamp = 'yyyy-MM-ddTHH:mm:ss.fffK'
$fmtDate      = 'yyyyMMdd'

$date = (Get-Date).AddDays($fromDay).ToUniversalTime().Date

$LogDate     = $date.ToString($fmtDate)
$StartTime   = $date.ToString($fmtTimestamp)
$EndUtcTime1 = $date.AddDays(1).AddMilliseconds(-1).ToString($fmtTimestamp)