ApplicationInsightsCustomEvents.psm1

<#
.SYNOPSIS
    Logs a custom event in Application Insights workspace
     
.DESCRIPTION
    Logs a custom event in Application Insights workspace. It takes an event dictionary<string,string> as input along with the Instrumentation Key and the event name.
     
.PARAMETER InstrumentationKey
  The instrumentation key of your Application Insights workspace.
 
.PARAMETER EventName
  The event name for your custom event.
 
.PARAMETER EventDictionary
  The event dictionary that holds the key-value pairs in <string,string> format.
   
.EXAMPLE
   $dictionary = New-Object 'System.Collections.Generic.Dictionary[string,string]'
   $dictionary.Add('Operation','Operation') | Out-Null
   $dictionary.Add('Username','Username') | Out-Null
   Log-ApplicationInsightsEvent -InstrumentationKey "InstrumentationKey" -EventName "CustomEventName" -EventDictionary $dictionary
 
.NOTES
    Author: Rohit Minni
    Date: September 27, 2016
#>


function Log-ApplicationInsightsEvent
{
    [CmdletBinding()]
    param(
            [Parameter(Mandatory=$true)][string] $InstrumentationKey,
            [Parameter(Mandatory=$true)][string] $EventName,
            [Parameter(Mandatory=$true)][object] $EventDictionary            
        )
    try
    {    
        $TelClient = New-Object -TypeName Microsoft.ApplicationInsights.TelemetryClient
        $TelClient.InstrumentationKey = $InstrumentationKey    
        $TelClient.TrackEvent($EventName, $EventDictionary)
        $TelClient.Flush()      
    }
    catch
    {
        Write-Output "Exception while logging into Application Insights: $($_.Exception.Message)"
    }  
}

Export-ModuleMember -Function Log-ApplicationInsightsEvent