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”,"Success",”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 + 2000} "Success" {$EventId = $ID + 5000} "Warning" {$EventId = $ID + 7000} "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 + "`r`n" #When a script triggerd this I'd like to know which script.. if (!($Invocation.StartsWith("<No file>"))) { $LogMessage += "`r`n" + "Script file and row: `n" + $Invocation } #When running on Azure Automation.. the $env:ComputerName is CLIENT. When it's not.. I'd like to know where it was running. IF ($env:COMPUTERNAME -ne "CLIENT") { $LogMessage += "`r`n" + "Running on: " + $env:COMPUTERNAME $LogMessage += "`r`n" + "Running as: " + $env:USERNAME } $LogMessage += "`r`n" + "`r`n" + "Log message generated by FortigiLoggingLibary version: " + (Get-Module FortigiLoggingLibary).Version Switch ($Type) { "Debug" { Write-Host $LogMessage -ForegroundColor Gray} "Info" { Write-Host $LogMessage -ForegroundColor White} "Success" { Write-Host $LogMessage -ForegroundColor Green} "Warning" {Write-Host $LogMessage -ForegroundColor DarkYellow} "Error" { Write-Host $LogMessage -ForegroundColor Red} } $TelClient.TrackEvent($LogMessage) $TelClient.Flush() } |