Skip to content

Instantly share code, notes, and snippets.

@JamesRandall
Last active May 2, 2023 13:39
Show Gist options
  • Save JamesRandall/444f3365751edb130bef197f2222cfa5 to your computer and use it in GitHub Desktop.
Save JamesRandall/444f3365751edb130bef197f2222cfa5 to your computer and use it in GitHub Desktop.
Powershell binding redirection
# Load your target version of the assembly
$newtonsoft = [System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll")
$onAssemblyResolveEventHandler = [System.ResolveEventHandler] {
param($sender, $e)
# You can make this condition more or less version specific as suits your requirements
if ($e.Name.StartsWith("Newtonsoft.Json")) {
return $newtonsoft
}
foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies()) {
if ($assembly.FullName -eq $e.Name) {
return $assembly
}
}
return $null
}
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)
# Rest of your script....
# Detach the event handler (not detaching can lead to stack overflow issues when closing PS)
[System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolveEventHandler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment