powershell 用 get-winevent 快速查看 windows 安全日志,支持筛选(如 id 4624/4625)、时间范围(starttime)、级别(level=2/3)、导出 csv 及简易实时轮询。
可以用 powershell 快速查看 windows 安全事件日志,核心命令是 get-winevent,它比传统事件查看器更灵活,支持筛选、排序、导出和批量分析。
快速查看最近的安全事件
执行以下命令可列出最近 10 条安全日志(ID 4624 表示成功登录,4625 表示登录失败):
Get-WinEvent -LogName Security -MaxEvents 10 | Format-List TimeCreated, Id, LevelDisplayName, Message若只想看登录相关事件,可加筛选:
Get-WinEvent -LogName Security -FilterHashtable @{LogName='Security'; ID=4624,4625} -MaxEvents 20按时间范围和严重级别筛选
安全日志量大,建议限定时间窗口和等级。例如,查今天发生的“错误”或“警告”级安全事件:
$Today = (Get-Date).DateGet-WinEvent -LogName Security -FilterHashtable @{LogName='Security'; StartTime=$Today; Level=2,3} | Select-Object TimeCreated, Id, LevelDisplayName, ProviderName
- Level=2 表示“错误”,Level=3 表示“警告”
- StartTime 支持精确到秒,也可用
(Get-Date).AddHours(-2)查两小时内事件 - ProviderName 可帮你识别来源(如 Microsoft-Windows-Security-Auditing)
导出为 CSV 便于分析
把结果保存成表格,方便用 Excel 或其他工具进一步处理:
Select-Object TimeCreated, Id, LevelDisplayName, @{Name='Account';Expression={$_.Properties[5].Value}}, @{Name='Workstation';Expression={$_.Properties[11].Value}} |
Export-Csv -Path "C:\security-logins.csv" -NoTypeInformation
说明:
- Properties[5] 通常对应登录账户名(索引因事件 ID 而异,4624 中常用 1/5/13)
- Properties[11] 常为源工作站名;实际使用前建议先用
$_.Properties | ForEach-Object {$_.Value}查看结构 - 导出前加
Where-Object { $_.Id -eq 4624 }可进一步细分
监控实时安全事件(简易轮询)
PowerShell 本身不提供原生实时流,但可用循环+时间戳实现近实时抓取:
$LastTime = Get-Datewhile ($true) {
$NewEvents = Get-WinEvent -LogName Security -FilterHashtable @{LogName='Security'; StartTime=$LastTime} -ErrorAction SilentlyContinue
if ($NewEvents) {
$NewEvents | Where-Object { $_.Id -in 4624,4625 } |
Format-Table TimeCreated, Id, LevelDisplayName, Message -AutoSize
$LastTime = $NewEvents[0].TimeCreated.AddMilliseconds(1)
}
Start-Sleep -Seconds 5
}
注意:该方式适合临时排查,生产环境建议搭配 Windows Event Forwarding 或 SIEM 工具。











