FortigiLoggingLibary.psm1

#######################################################################################################
# FortigiLogging
#
# By Maatschap Fortigi
# Wim van den Heijkant (Wim@Fortigi.nl)
#
#######################################################################################################

Function Write-AILog {
    Param (
        [Parameter(Mandatory=$True)]
        [string]$AIKey,
        [Parameter(Mandatory=$True)]
        $LogMessage,
        [parameter(Mandatory = $true)]
        [ValidateSet(“Debug”,”Info”,”Warning”,"Error")] 
        [string] $Type,
        [parameter(Mandatory = $false)]
        [ValidateRange(0, 999)]
        [int] $ID
        ) 

    #Load ApplicationInsights DLL
    $Dll = Get-Item "$PSScriptRoot\Microsoft.ApplicationInsights.dll"
    $NoCli = [Reflection.Assembly]::UnsafeLoadFrom($Dll)

    $InstrumentationKey = $AIKey
    $TelClient = New-Object "Microsoft.ApplicationInsights.TelemetryClient"
    $TelClient.InstrumentationKey = $InstrumentationKey

    Switch ($Type) {
        "Debug" {$EventId = $ID + 1000}
        "Info" {$EventId = $ID + 3000}
        "Warning" {$EventId = $ID + 5000}
        "Error" {$EventId = $ID + 8000}
        }

    #Build the invocation information
    $PSCallStack = Get-PSCallStack | SELECT -Skip 1 #Remove first element, as this is the log function itself
    #If($PsCallStack.Count -gt 1){$PSCallStack = Select -First $($PSCallStack.Count-1)} #Remove last element, as this is the command line which invoked the command
    
    $Invocation = ""
    Foreach ($Call in $PSCallStack) {
        $Invocation += $Call.Location                                          #Script Name without the complete path, including line number
        $Invocation += "/$($Call.Command) $($Call.Arguments)"                  #Command/Function, including arguments
        $Invocation += ' | '
        }

    $LogMessage = $EventId.ToString() + ":" + $LogMessage

    if (!($Invocation.StartsWith("<No file>"))) {
        $LogMessage += $LogMessage + "`n" + "Script file and row: `n" + $Invocation
        }
    
    $LogMessage += $LogMessage + "`n" + "Log message generated by FortigiLoggingLibary version: " + (Get-Module FortigiLoggingLibary).Version

    Write-Host $LogMessage
    $TelClient.TrackEvent($LogMessage)
    $TelClient.Flush()
            
    }