Public/Write-ECKLog.ps1

Function Write-ECKlog
    {
        #Can use $Script variables $Script:LogDir, $Script:DontLogNow, $Script:EnableConsoleLogging

        # Version 1.3 - 14/02/2022 - replaced write-host by Write-output
        # Version 1.4 - 21/02/2022 - changed $Script scopte variable to work with Module

        [CmdletBinding()]
        [Alias('Write-Log')]
        Param(
              [parameter()]
              [String]$Path = $(If ($LogDir) {[string]::Format("{0}\{1}.log", $LogDir, $($MyInvocation.MyCommand.Name).Replace(".ps1", ""))} Else {[string]::Format("{0}\{1}.log", 'C:\Windows\logs', $($MyInvocation.MyCommand.Name).Replace(".ps1", ""))}),
              [parameter(Position=0, Mandatory=$true, HelpMessage="Please provide a message to log !")]
              [String]$Message,
              [parameter()]
              [String]$OutputToConsole = $true,
              [parameter()]
              [String]$EventLogID,
              [parameter()]
              [Switch]$EventLogOnly,
              #Severity Type(1 - Information, 2- Warning, 3 - Error)
              [parameter(Mandatory=$False)]
              [ValidateRange(1,3)]
              [Int]$Type = 1
        )

        $oDate = $(Get-Date -Format "M-d-yyyy")
        $oHour = $(Get-Date -Format "HH:mm:ss")
        $MessageType = @{1 = "Information"; 2 = "Warning"; 3 = "Error"}
        $Tab = [char]9

        # Create a log entry
        $Content = "$oDate $oHour, $($MessageType[$type]) $Tab $($Message -replace "`r`n", ", ")"

        # Write the line to the log file
        If ($DontLogNow -ne $true -and (-not $EventLogOnly)) # $DontLogNow must be defined outside the function like this $Script:DontLogNow = $True
            {
                $Content| Out-file -FilePath $Path -Encoding UTF8 -Append -ErrorAction SilentlyContinue

                If ($OutputToConsole -eq $true -and $EnableConsoleLogging -ne $false){Write-output $Content} # $EnableConsoleLogging must be defined outside the function like this $Script:EnableConsoleLogging =$False
            }

        If ($EventLogID)
            {
                $AppriendlyName = $($MyInvocation.MyCommand.Name) -replace "-" ,"" -replace ".ps1","" -replace " ",""
                If ([System.Diagnostics.EventLog]::SourceExists($AppriendlyName) -eq $false){New-EventLog -LogName "Application" -Source $AppriendlyName}
                Write-EventLog -LogName "Application" -Source $AppriendlyName -EventID $EventLogID -EntryType $($MessageType[$type]) -Message $Message -Category 0
            }
    }