Windows 11 如何定期匯出事件檢視器安全性

Windows 11 如何定期匯出事件檢視器安全性

事件檢視器 – 安全性,可以看到關於登入、驗證等訊息,對於稽核來說,可以作為連線、使用依據。

使用powershell可以透過指令匯出事件檢視器-安全性,要注意,這是Powershell而不是cmd(字元提示命令),並且在執行重大指令時,記得需要提升權限等級,像是使用系統管理員權限執行。

為了要定期保存,這邊會使用Windows內建的「工作排程器」。

這是一個較為常見的需求,相關內容我是透過ChatGPT得到,並且驗證有用。

https://chatgpt.com/share/688825cb-7f30-8003-88ab-4f0288d8ec82

Powershell腳本

腳本中有保存路徑「$dest」,依照需求調整。

# backup-securitylog.ps1
$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$dest  = "C:\EventBackups\Security_$stamp.evtx"

# 匯出安全性事件
wevtutil epl Security $dest

# (選用)匯出後清空並備份:wevtutil cl Security /bu:$dest
# 建議視稽核/法遵需求再決定是否清空

Powershell腳本執行結果

如果直接使用「用 PowerShell 執行」,因為權限不足,會無法輸出內容。

開始 > 終端機(系統管理員),就能以系統管理員權限執行PowerShell。

對腳本按右鍵,可以複製其路徑。然後貼上到powershell,並且刪去前後雙引號。

#
<script path>

# Example
C:\export_security.ps1

順利產生事件紀錄檔,雙擊打開,可以看到保存下來的紀錄

工作排程器

開始 > 搜尋「工作排程器」

新增一個基本工作,觸發程序與排程依照自己需求調整,「動作」則依照以下去新增

動作:啟動程式 → 
程式/指令:powershell.exe
參數:-File "<script path>"

# Exmaple
參數:-File "C:\Scripts\backup-securitylog.ps1"

記得勾選「以最高權限執行」。

測試工作排程器是否正常

針對排程任務,右鍵,執行。

正常會短暫跳出PowerShell的視窗。

順利產生新的事件檢視器紀錄檔

事件檢視器安全性記錄檔壓縮並定期清除舊備份的腳本範本

# 參數設定
$backupDir = 'C:\Logs'
$dateStr   = Get-Date -Format 'yyyyMMdd'
$evtxFile  = Join-Path $backupDir "SecurityLog_$dateStr.evtx"
$zipFile   = Join-Path $backupDir "SecurityLog_$dateStr.zip"

# 1. 以管理員身分執行檢查
$identity  = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Error '請以系統管理員身分執行此腳本。'
    exit 1
}

# 2. 確保備份目錄存在
if (-not (Test-Path $backupDir -PathType Container)) {
    New-Item -ItemType Directory -Path $backupDir -Force | Out-Null
}

try {
    # 3. 匯出安全性事件
    Start-Process -FilePath 'wevtutil' `
        -ArgumentList "epl Security $evtxFile /ow:true" `
        -NoNewWindow -Wait -PassThru |
        Out-Null

    # 4. 驗證檔案存在
    if (-not (Test-Path $evtxFile -PathType Leaf)) {
        throw "匯出失敗:找不到 $evtxFile"
    }

    # 5. 壓縮(使用 Splatting)
    $zipParams = @{
        Path             = $evtxFile
        DestinationPath  = $zipFile
        CompressionLevel = 'Fastest'
        Force            = $true
        ErrorAction      = 'Stop'
    }
    Compress-Archive @zipParams

    # 6. 刪除原始 EVTX
    Remove-Item $evtxFile -Force -ErrorAction Stop
}
catch {
    Write-Error "錯誤發生:$($_.Exception.Message)"
    exit 1
}

# 7. 清理 30 天前舊備份(相容 PS v2+)
Get-ChildItem -Path $backupDir -Filter '*.zip' |
  Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
  Remove-Item -Force -ErrorAction SilentlyContinue