This function simplifies the process of using the Write-EventLog cmdlet.  In order to use the Write-EventLog cmdlet, input required is a valid registered event log and the corresponding event log itself.  The function will detect where an event source is registered and write the event log entry to that log.  Alternatively, it will register the event source (if it is not already registered) to the desired log and then log the desired event to the appropriate log.

 

 

 

 

PowerShell
Edit|Remove
function Log-Event { 
    param( 
        [Parameter(Mandatory=$true)] 
        [ValidateNotNullorEmpty()] 
        [String]$Message, 
 
        [ValidateNotNullorEmpty()] 
        [String]$Source = "ScriptOutput", 
 
        [int32]$EventID = 1, 
 
        $LogName = "Application", 
 
        [System.Diagnostics.EventLogEntryType]$Type = "Information" 
    ) 
    try { 
        $SourceLogName = [System.Diagnostics.EventLog]::LogNameFromSourceName($source".") 
        if (![string]::IsNullOrEmpty($SourceLogName)) { 
            Write-EventLog -LogName $SourceLogName -Source $Source -Message $Message -EntryType $Type -EventId $EventID 
        } 
        else { 
            New-EventLog -Source $Source -LogName $LogName 
            #After register new event source, do not use right away, accoring to MSDN: 
            #http://msdn.microsoft.com/en-us/library/2awhba7a(v=vs.110).aspx 
            Sleep 5 
            Write-EventLog -LogName $LogName -Source $Source -Message $Message -EntryType $Type -EventId $EventID 
        } 
    } 
    catch { 
        Write-Warning "Unexpected error occured while attempting to write to log." 
        Write-Warning "Caller command: $((Get-PSCallStack)[1].Command)" 
        Write-Warning "Error: $($_.exception.message)" 
    } 
}