Azure Runbook load .Net assembly for application i

2019-09-03 07:54发布

问题:

I have requirement where I want to write some metrics to the application insight for monitoring a service at a regular interval.

I though that I would write this PowerShell script and schedule it accordingly.

Write-Output "Script Start"
$PSScriptRoot = Get-Location
$AI = "$PSScriptRoot\Microsoft.ApplicationInsights.dll"
[Reflection.Assembly]::LoadFile("$AI")
$InstrumentationKey = ""
$TelClient = New-Object "Microsoft.ApplicationInsights.TelemetryClient"
$TelClient.InstrumentationKey = $InstrumentationKey

$TrackMetric = New-Object "Microsoft.ApplicationInsights.DataContracts.MetricTelemetry"
$TrackMetric.Name = "PowershellTest"
$TrackMetric.Value = Get-Random -Minimum:1 -Maximum:100

$TelClient.TrackMetric($TrackMetric)
$TelClient.Flush()

Write-Output "Script End  $TrackMetric.Value"

This PowerShell Script works, but after I moving that script to Runbook it is no longer working.

So, here is the issue. I am not able to load the ApplicationInsight DLL inside the Runbook.

Any idea how to do that?

Exception Details

Exception calling "LoadFile" with "1" argument(s): "The system cannot find the file specified. (Exception from HRESULT: 
0x80070002)"

Thanks Siraj

回答1:

Try following path for the assembly "C:\Modules\Global\Azure\Compute\Microsoft.ApplicationInsights.dll"



回答2:

The issue is in loading the DLL file. The Runbook is not able to find the file in this line:

$AI = "$PSScriptRoot\Microsoft.ApplicationInsights.dll"
[Reflection.Assembly]::LoadFile("$AI")

When you run a Runbook via Azure Automation, you don't have access to the local path as you normally do on a local machine or on premise. In Azure Automation, modules are placed in "C:\Modules".

Instead, use below code snippet, after you have uploaded the dll file:

[System.Reflection.Assembly]::LoadFrom("C:\Modules\Azure\Microsoft.ApplicationInsights.dll")

Closest Related Reference: Referencing DLL