Azure自动化帐户PowerShell Runbook中的绑定重定向

问题描述

在Azure自动化帐户运行手册中设置PowerShell绑定重定向时,我需要一些帮助。

基本上,我的Runbook调用了两个第三方.Net dll中的许多方法,这两个方法均由同一作者提供。其中一个dll依赖于Newtonsoft.Json V12.0.1,另一个dll依赖于IdentityModel V4.0.0,而IdentityModel V4.0.0又依赖于Newtonsoft.Json V11.0.2。我的Azure环境使用Windows PowerShell桌面V5.1.15063.726。在Runbook中进行任何工作之前,我会调用一个函数,该函数会在导入的模块中加载所有dll(该函数为每个dll调用[System.Reflection.Assembly] :: LoadFrom()方法)。我已验证我导入的dll(包括Newtonsoft.Json.dll V12.0.1)已成功加载。

按预期,当Runbook执行到达调用需要IdentityModel.dll的第三方dll方法之一的行时,将引发异常: 带有“ 0”参数的异常调用“ GetResult”:“无法加载文件或程序集'Newtonsoft.Json,版本= 11.0.0.0,Culture =中性,PublicKeyToken = 30ad4fe6b2a6aeed”或其依赖项之一。系统找不到指定的文件。” System.IO.FileNotFoundException。

这是一个已知问题,到目前为止,共识似乎是我需要在PowerShell中创建并附加事件处理程序。可以在here中找到建议的解决方案之一。我的问题是尝试附加处理程序的行:

[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)

当Runbook命中此行时,将引发以下异常: 找不到“ add_AssemblyResolve”和参数计数:“ 1”的重载。 TargetSite:无效CheckActionPreference(System.Management.Automation.Language.FunctionContext,System.Exception)StackTrace:位于System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext,Exception异常)

我可以确认,非常有限的测试似乎证明了使用PowerShell ISE的代码可以在Windows 8.1中运行。我进行了广泛的搜索,以查看在Azure和Windows Desktop中应如何编写此代码之间是否有区别,但是没有运气。谁能看到我做错了吗?我是否缺少任何DLL或使用PowerShell脚本中的语句?如果无法以这种方式重定向绑定,那么有人可以提供替代技术吗?

下面是显示事件处理程序的创建和附件的代码摘录:

# Intercept resolution of binaries
$onAssemblyResolveEventHandler = [System.ResolveEventHandler]
{
    param($sender,$e)

    Write-Host "ResolveEventHandler: Attempting FullName resolution of $($e.Name)" 
    foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies()) 
    {
        if ($assembly.FullName -eq $e.Name)
        {
            Write-Host "Successful FullName resolution of $($e.Name)" 
            return $assembly
        }
    }

    Write-Host "ResolveEventHandler: Attempting name-only resolution of $($e.Name)" 
    foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies())
    {
        # Get just the name from the FullName (no version)
        $assemblyName = $assembly.FullName.Substring(0,$assembly.FullName.IndexOf(","))

        if ($e.Name.StartsWith($($assemblyName + ","))) 
        {
            Write-Host "Successful name-only (no version) resolution of $assemblyName" 
            return $assembly
        }
    }

   Write-Host "Unable to resolve $($e.Name)" 
    return $null
}   
# Attach event handler
# This is the line that fails.
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)

解决方法

我无法通过在Azure自动化帐户-PowerShell Runbook环境中进行绑定重定向来解决问题,但是两个第三方.Net dll的作者都同意使用NewtonSoft.Json 11.0版。两个DLL都为2,所以我的问题消失了。