Gateway-keepaliveForPowershell/logger.ps1

42 lines
1.2 KiB
PowerShell

. $(-Join($(Get-Location).Path, '\config.ps1'))
function Write-Log {
param (
[Parameter(Mandatory)]
[string]$Message, # 日志内容
[switch]$ToEventLog # 是否输出到事件管理器
)
# 时间戳前缀
$timestamp = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
$logEntry = "[$timestamp] $Message"
# 输出到控制台
if ($Global:isDebugging) {
Write-Host $logEntry
}
if ($ToEventLog){
# 写入到 Windows 事件日志
$eventID = 1000
# 确保事件源存在
$source = "GateWay-KeepAliveForPowershell"
if (-not (Get-EventLog -LogName Application -Source $source -ErrorAction SilentlyContinue)) {
try {
New-EventLog -LogName Application -Source $source -ErrorAction Stop
} catch {
Write-Host "Error creating event source: $_" -ForegroundColor Red
return
}
}
# 写入事件日志
try {
Write-EventLog -LogName Application -Source $source -EventID $eventID -EntryType 'Info' -Message $Message
} catch {
Write-Host "Failed to write to event log: $_" -ForegroundColor Red
}
}
}