Last active
November 20, 2023 23:23
-
-
Save RylandDeGregory/c32359c11ff800d81867581fdc4024e4 to your computer and use it in GitHub Desktop.
PowerShell and AppInsights sample code and binary library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Requires Microsoft.ApplicationInsights.dll from: https://www.nuget.org/packages/Microsoft.ApplicationInsights/ ## | |
## Unzip the .nupkg file and extact the "lib/net452/Microsoft.ApplicationInsights.dll" ## | |
## Upload the .dll to the same directory as "run.ps1" within the Function App | |
# Load .dll assembly into PowerShell session | |
[Reflection.Assembly]::LoadFile("$PSScriptRoot\Microsoft.ApplicationInsights.dll") | |
# Instantiate the Telemetry Client configuration | |
$TelemetryClientConfig = [Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration]::CreateDefault() | |
# Set the Application Insights Connection String | |
$TelemetryClientConfig.ConnectionString = '<AppInsights Connection String>' | |
# Instantiate a new Telemetry Client using the defined configuration | |
$TelemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new($TelemetryClientConfig) | |
# Generate a custom event | |
$TelemetryClient.TrackEvent('This is my custom AppInsights event') | |
$TelemetryClient.Flush() | |
# Generate a custom exception | |
$TelemetryClient.TrackException('This is my custom AppInsights exception') | |
$TelemetryClient.Flush() | |
try { | |
# Throw an exception | |
0/0 | |
} catch { | |
# Record the caught exception | |
$TelemetryClient.TrackException($_.Exception) | |
$TelemetryClient.Flush() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @e-karlsson,
The gist is meant to demonstrate the most basic implementation of App Insights telemetry capture using PowerShell. If you dig into the .NET SDK and the available properties/constructors for Requests, Exceptions, Traces, etc. you'll find that you can do a lot more.
To add an Operation ID to your Events, you have to manually inject an
operationId
value into the Event record by using theEventTelemetry
overload for the.TrackEvent()
method. You can do so using the sample code below. You can also set a lot more properties within theEventTelemetry
object's TelemetryContext.