Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active October 29, 2022 02:34
Show Gist options
  • Save akunzai/3d76a08afeaf70775ab366fe9051e750 to your computer and use it in GitHub Desktop.
Save akunzai/3d76a08afeaf70775ab366fe9051e750 to your computer and use it in GitHub Desktop.
Optimize assembly binding redirection in web.config or app.config
# https://learn.microsoft.com/zh-tw/dotnet/framework/configure-apps/redirect-assembly-versions
<#
.Synopsis
Optimize assembly binding redirection in web.config or app.config
.EXAMPLE
. .\Optimize-AssemblyBinding.ps1; sort-binding -path .\web.config
. .\Optimize-AssemblyBinding.ps1; sort-binding -path .\web.config -whatIf
#>
function Optimize-AssemblyBinding(){
Param (
[Parameter(Mandatory=$True)]
[string]$path,
[Parameter(Mandatory=$False)]
[Switch]
[bool]$whatIf=$false
)
$assemblyBinding = Select-Xml -Path $path -XPath '//configuration/runtime/x:assemblyBinding' -Namespace @{ x="urn:schemas-microsoft-com:asm.v1" }
if (!$assemblyBinding.Node.HasChildNodes){
Write-Warning "//configuration/runtime/assemblyBinding section not found!"
exit 1
}
$dependentAssembles = $assemblyBinding.Node.SelectNodes('*') | Sort-Object {$_.assemblyIdentity.name}
$output = if ($whatIf) { New-Object System.IO.StringWriter } else { Resolve-Path $path }
if (Compare-Object -ReferenceObject $assemblyBinding.Node.dependentAssembly -DifferenceObject $dependentAssembles -Property {$_.assemblyIdentity.name} -SyncWindow 0){
$assemblyBinding.Node.RemoveAll();
foreach( $dependentAssemble in $dependentAssembles ){
[void]$assemblyBinding.Node.AppendChild($dependentAssemble)
}
$assemblyBinding.Node.OwnerDocument.Save($output)
}
if ($output.GetType() -eq [System.IO.StringWriter]){
Write-Output $output.ToString()
}
}
Set-Alias sort-binding Optimize-AssemblyBinding
@akunzai
Copy link
Author

akunzai commented Jul 10, 2020

# Execute the script directly from URL
iwr -useb https://gist.githubusercontent.com/akunzai/3d76a08afeaf70775ab366fe9051e750/raw/Optimize-AssemblyBinding.ps1 | iex; sort-binding -path ./web.config

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment