Repair-Pfa2AsemblyBinding.ps1

# Default the Pfa2Directory to the directory of the entry script for the task.
if (!$Pfa2Directory) {
    $Pfa2Directory = [System.IO.Path]::GetFullPath("$PSScriptRoot")
    Write-Verbose "Defaulted PFA2 directory to: '$Pfa2Directory'"
}

# Test if the System.Buffers DLL exists in the PFA2 directory.
$global:pfa2SystembBffersDllPath = [System.IO.Path]::Combine($Pfa2Directory, "System.Buffers.dll")
Write-Verbose "Testing file path: '$global:pfa2SystembBffersDllPath'"
if (!(Test-Path -LiteralPath $global:pfa2SystembBffersDllPath -PathType Leaf)) {
    Write-Error 'Path not found: $($global:pfa2SystembBffersDllPath). Rethrowing exception.'
    throw
}
# Test if the Newtonsoft DLL exists in the PFA2 directory.
$global:pfa2NewtonsoftDllPath = [System.IO.Path]::Combine($Pfa2Directory, "Newtonsoft.Json.dll")
Write-Verbose "Testing file path: '$global:pfa2NewtonsoftDllPath'"
if (!(Test-Path -LiteralPath $global:pfa2NewtonsoftDllPath -PathType Leaf)) {
    Write-Error 'Path not found: $($global:pfa2NewtonsoftDllPath). Rethrowing exception.'
    throw
}

$onAssemblyResolve = [System.ResolveEventHandler] {
    param($sender, $e)

    if ($e.Name -like 'System.Buffers, *') {
        Write-Verbose "Resolving '$($e.Name)'"
        return [System.Reflection.Assembly]::LoadFrom($global:pfa2SystembBffersDllPath)
    }
    if ($e.Name -like 'Newtonsoft.Json, *') {
        Write-Verbose "Resolving '$($e.Name)'"
        return [System.Reflection.Assembly]::LoadFrom($global:pfa2NewtonsoftDllPath)
    }

    Write-Verbose "No PFA2 BindingRedirect for assembly name '$($e.Name)'"
    return $null
}
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)