Last active
August 31, 2017 01:50
-
-
Save crossan007/c8c88e110a87f8a89cd2ecac8e126edc to your computer and use it in GitHub Desktop.
PowerShell Logging Tee Function App -> Windows Event Log && Terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.EXAMPLE | |
Write-PSEventLog @LogParams -EntryType Information -EventId 100 -Message "Starting Installation" | |
#> | |
#region SetupLogging | |
$LogParams =@{ | |
'LogName' = '<LOG NAME: Application|Setup|System|Security>'; | |
'Source' = '<Your Custom Script Name>' | |
} | |
if(![System.Diagnostics.EventLog]::SourceExists($LogParams.Source)) | |
{ | |
New-EventLog @LogParams | |
} | |
Function Write-PSEventLog { | |
<# | |
.SYNOPSIS | |
Wrapper function to split Logging to the windows event log and to the terminal | |
#> | |
param( | |
$LogName, | |
$Source, | |
$EventId, | |
$EntryType, | |
$Message | |
) | |
if (-not $PSBoundParameters.ContainsKey('EventID')) | |
{ | |
$PSBoundParameters['EventID'] = "1" | |
$PSBoundParameters['Message'] = "[$($(get-PSCallStack)[1].Location)]: $Message" | |
} | |
if (-not $PSBoundParameters.ContainsKey('EntryType')) | |
{ | |
$PSBoundParameters['EntryType'] = "Information" | |
} | |
Switch($PSBoundParameters['EntryType']) | |
{ | |
"Error" { | |
write-host -ForegroundColor Red $PSBoundParameters['Message'] | |
} | |
"Information" { | |
write-host -ForegroundColor Green $PSBoundParameters['Message'] | |
} | |
} | |
try{ | |
Write-EventLog @PsBoundParameters | |
} | |
catch { | |
throw "Error writing to Windows Event Log. Reason: $($_.Exception.Message)" | |
} | |
} | |
#endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment