diff --git a/StackMonkey.ps1 b/StackMonkey.ps1 index 51b8040..55e3f74 100644 --- a/StackMonkey.ps1 +++ b/StackMonkey.ps1 @@ -331,32 +331,36 @@ } # ─── Event Log ────────────────────────────────────────────────── - if ($LogToEvent) { - # 1) Ensure your custom source/log exist - if (-not [System.Diagnostics.EventLog]::SourceExists($EventSource)) { - New-EventLog -LogName $EventLog -Source $EventSource - } + if ($LogToEvent) { + try { + # 1) Ensure your custom source/log exist + if (-not [System.Diagnostics.EventLog]::SourceExists($EventSource)) { + New-EventLog -LogName $EventLog -Source $EventSource -ErrorAction Stop + } + } catch { + Write-Host "[Warning] Could not create event log '$EventLog' or source '$EventSource': $($_.Exception.Message)" -ForegroundColor Yellow + return + } - # 2) Map level to entry type - $entryType = if ($Level -in 'Warning','Error') { $Level } else { 'Information' } + # 2) Map level to entry type + $entryType = if ($Level -in 'Warning','Error') { $Level } else { 'Information' } - # 3) Write to the Windows event log - try { - Write-EventLog ` - -LogName $EventLog ` - -Source $EventSource ` - -EntryType $entryType ` - -EventID $EventID ` - -Message $fmt - } - catch { - Write-Host "[Warning] EventLog failed: $_" -ForegroundColor Yellow - } - } + # 3) Write to the Windows event log + try { + Write-EventLog ` + -LogName $EventLog ` + -Source $EventSource ` + -EntryType $entryType ` + -EventID $EventID ` + -Message $fmt + } + catch { + Write-Host "[Warning] EventLog failed: $($_.Exception.Message)" -ForegroundColor Yellow + } + } - # ─── PassThru ──────────────────────────────────────────────────── - if ($PassThru) { return $Global:LogCache[-1] } - } + if ($PassThru) { return $Global:LogCache[-1] } + } # ───────────────────────────────────────────────────────────────────────── # WRITE-LOG HYBRID (single definition, chooses at runtime if we use the