functions/Send-THEvent.ps1

<#
.SYNOPSIS
    Send custom event
.DESCRIPTION
    Send custom event with configurable properties and metrics. This is the most versatile
    telemetry instrument. Properties and Metrics can all be evaluated in e.g. PowerBI or an AppInsights query.
.PARAMETER EventName
    Name of the event
.PARAMETER Properties
    Dictionary of properties and their values.
.PARAMETER Metrics
    Dictionary of metrics and their values
.PARAMETER ModuleName
    Auto-generated, used to select the proper configuration in case you have different modules
.EXAMPLE
    Send-THEvent -EventName ModuleImport -Properties @{PSVersionUsed = $PSVersionTable.PSVersion}
 
    Sends a ModuleImport event with the PowerShell Version that has been used.
#>

function Send-THEvent
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $EventName,

        [Parameter()]
        [System.Collections.Generic.Dictionary[string, string]]
        $Properties,

        [Parameter()]
        [System.Collections.Generic.Dictionary[string, double]]
        $Metrics,

        [Parameter()]
        [string]
        $ModuleName = (Get-CallingModule)
    )

    begin
    {
        $telemetryInstance = Get-THTelemetryConfiguration -ModuleName $ModuleName
    }

    process
    {
        
        try
        {
            if ($Properties -and $Metrics)
            {
                $telemetryInstance.SendEvent($EventName, $Properties, $Metrics)
            }
            elseif ($Properties)
            {
                $telemetryInstance.SendEvent($EventName, $Properties)
            }
            elseif ($Metrics)
            {
                $telemetryInstance.SendEvent($EventName, $null, $Metrics)
            }
            else
            {
                $telemetryInstance.SendEvent($EventName)
            }
        }
        catch
        {
            Stop-PSFFunction -Message "Unable to send event $EventName to ApplicationInsights" -Exception $_.Exception
        }
    }

    end
    {
        try
        {
            $telemetryInstance.Flush()
        }
        catch
        {
            Stop-PSFFunction -Message "Unable to flush telemetry client. Messages may be delayed." -Exception $_.Exception
        }
    }
}