如何從 PowerShell/CMD 將日誌寫入 Windows 事件查看器

Jacki

除了在腳本中使用文本日誌文件之外,您還可以將事件信息直接寫入事件查看器日誌。在本文中,我們將了解如何從 PowerShell 腳本或命令提示符將日誌寫入 Windows 事件查看器。

要將信息寫入 Windows 事件日誌,請使用寫事件日誌cmdlet。例如,要將信息事件寫入應用程序日誌:

Write-EventLog -LogName Application -Source "Application" -EntryType Information -EventID 1 -Message "PS1 Script started"

您可以將單獨的事件源添加到現有日誌中:

New-EventLog -LogName Application -Source "MyScripts"

現在,您可以使用自定義源編寫事件:

Write-EventLog -LogName Application -Source "MyScripts" -EntryType Warning –EventID 1 –Message "PS1 Script started"

打開事件查看器控制台(eventvwr.msc),展開應用日誌,並檢查帶有您的描述的新事件是否已添加到日誌中。

可以在以下事件類型中使用條目類型範圍:Error,Information,FailureAudit,SuccessAudit, 或者Warning

要將事件從 BAT/CMD 腳本添加到日誌,請使用 eventcreate.exe 命令:

eventcreate /t information /l application /id 1 /d "BAT script started"

您可以使用事件查看器中創建自定義經典事件日誌新事件日誌命令。

New-EventLog -LogName CustomPSLog -source 'MyScripts','PSScript','PSLogonScript','PSSchedScript'

如果要將事件寫入自定義日誌,則應首先檢查腳本以查看該日誌是否已存在。
If ([System.Diagnostics.EventLog]::SourceExists('CustomPSLog') -eq $False) {
New-EventLog -LogName CustomPSLog -Source ...
}

為了使新的經典事件日誌出現在事件查看器圖形控制台中,您必須至少向其發送一個事件。

Write-EventLog -LogName CustomPSLog -Source MyScripts -EntryType Information -EventID 1 -Message "Test"

根目錄中將出現一條新日誌應用程序和服務日誌部分。將為日誌文件創建一個新的 EVTX 文件%SystemRoot%System32WinevtLogs文件夾。

了解如何在 Windows 上配置最大事件日誌大小和其他選項。

了解更多:使用 Windows 事件查看器日誌跟踪打印機使用情況

使用 Get-WinEvent cmdlet 查找並篩選事件查看器日誌中的事件:

Get-WinEvent -FilterHashtable @{logname="CustomPSLog";id=1}|ft TimeCreated,Id,Message | Select-Object -First 5

在最新版本的 PowerShell Core 中,不支持 Write-EventLog cmdlet。如果您嘗試運行包含它的命令,您將收到錯誤:

Write-EventLog: The term 'Write-EventLog' is not recognized as a name of a cmdlet, function, script file, or executable program.

在 PowerShell Core 7.x 中,您應該使用新贏活動反而。但是,要使用它,您需要註冊一個單獨的事件提供程序,這可能很複雜。在 PowerShell Core 腳本中,首先使用以下命令導入 Microsoft.PowerShell.Management 模塊要容易得多-UseWindowsPowerShell選項。然後,您可以在 PowerShell Core 腳本中使用 Write-EventLog cmdlet:

Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
Write-EventLog -LogName CustomPSLog1 -Source CustomPSLog -EntryType Information -EventID 1 -Message "Test2"

要使用 Write-EventLog cmdlet 將日誌添加到事件查看器,請使用本地管理員組成員的帳戶。非管理員用戶只能將事件發送到管理員創建的自定義事件查看器日誌。