如何从PowerShell/CMD写入Windows事件查看器
或者,要在脚本中使用文本日志文件,您可以将事件信息直接写入事件查看器日志。在本文中,我们将查看如何通过PowerShell脚本或命令提示符将日志写入Windows事件查看器。
要将信息写入Windows事件日志,请使用Write-Eventlogcmdlet。例如,将信息事件写入应用程序日志:
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),扩展应用日志,并检查是否将带有您描述的新事件添加到日志中。

以下事件类型可以在EntryType范围:Error,,,,Information,,,,FailureAudit,,,,SuccessAudit, 或者Warning。
要从BAT/CMD脚本中添加事件,请使用EventCreate.exe命令:
eventcreate /t information /l application /id 1 /d "BAT script started"


您可以在事件查看器中创建自定义的经典事件日志新Eventlog命令。
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上配置最大事件日志大小和其他选项。
使用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将日志添加到事件查看器中,请使用本地管理员组成员的帐户。非ADMIN用户只能将事件发送到由管理员创建的自定义事件查看器日志。
