要在 PowerShell 脚本中将错误日志写入 Windows 事件查看器,我找到了合适的源
Application Error
和事件 ID 1000
。
当您拨打
Write-EventLog -LogName "Application" -Source "Application Error" -EventId "1000" -Message "TEST MESSAGE"
时,事件日志消息将如下所示:
Faulting application name: TEST MESSAGE, version: %2, time stamp: 0x%3
Faulting module name: %4, version: %5, time stamp: 0x%6
Exception code: 0x%7
Fault offset: 0x%8
Faulting process id: 0x%9
Faulting application start time: 0x%10
Faulting application path: %11
Faulting module path: %12
Report Id: %13
Faulting package full name: %14
Faulting package-relative application ID: %15
我找不到从
%2
正确设置参数 %3
、Write-EventLog
...的方法。
-Message
参数设置为 %1
作为字符串。-RawData
参数设置为%2
,但它被解释为十六进制字符串。例如,当您传递参数-RawData $utf8Encoding.GetBytes("1.2.7")
时,消息将显示为version: 312E322E37
。我期待的结果是version: 1.2.7
。有没有办法使用 PowerShell 在 Windows 事件日志消息中设置参数
%2
、%3
、...?
PowerShell API 在通过消息传递特定于提供者的参数方面似乎受到限制。您可以使用 .NET API
System.Diagnostic.EventLog
来代替:
# Create an EventLog instance for the Application log
$eventLog = [System.Diagnostics.EventLog]::new('Application')
$eventLog.Source = 'Application Error'
# Write the event with parameters
$eventLog.WriteEvent(
[System.Diagnostics.EventInstance]::new(1000, 0, [System.Diagnostics.EventLogEntryType]::Error),
@(
'DummyApp.exe', # Application name
'1.2.3.4', # Application version
'12345678', # Time stamp
'dummyModule.dll', # Faulting module name
'2.3.4.5', # Module version
'87654321', # Module time stamp
'c0000005', # Exception code
'0000000000012345', # Fault offset
'0x1234', # Process ID
'0x5D3E7F22', # Application start time
'C:\Program Files\DummyApp\DummyApp.exe', # Application path
'C:\Windows\System32\dummyModule.dll', # Module path
'dummy-report-id-1234abcd', # Report ID
'dummy-package-name', # Faulting package full name
'dummyapp-id' # Faulting package-relative application ID
)
)