Last active
February 8, 2016 16:09
-
-
Save guitarrapc/72bffd1e1c12bec100f9 to your computer and use it in GitHub Desktop.
Assembly.Load() then Import-Module as DynamicModule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load Assembly without dll Lock | |
function LoadAssembly ([System.Reflection.AssemblyName[]]$Arr, [string]$Directory) | |
{ | |
$loadeAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies(); | |
$names = New-Object System.Collections.Generic.List[string]; | |
foreach ($assem in $loadeAssemblies) | |
{ | |
$names.Add($assem.FullName); | |
} | |
foreach ($anam in $Arr) | |
{ | |
if (! ($names.Contains($anam.FullName))) | |
{ | |
try | |
{ | |
[byte[]]$binary = [System.IO.File]::ReadAllBytes((Join-Path $Directory $anam.Name) + ".dll"); | |
$loadeAssembly = [System.Reflection.Assembly]::Load($binary); | |
$referencedAssemblies = $loadeAssemblies.GetReferencedAssemblies(); | |
LoadAssembly($referencedAssemblies, $Directory); | |
} | |
catch | |
{ | |
} | |
} | |
} | |
} | |
# Load Assembly as byte[] and Import Module as DynamicModule | |
function ImportModuleToCurrentAppDomain ([string]$Path) | |
{ | |
[byte[]]$primary = [System.IO.File]::ReadAllBytes($Path); | |
$assembly = [System.Reflection.Assembly]::Load($primary); | |
$arr = $assembly.GetReferencedAssemblies(); | |
LoadAssembly -Arr $arr -Directory (Split-Path $Path -Parent); | |
return (Import-Module -Assembly $assembly -PassThru); | |
} | |
# Find Module Path | |
$moduleName = "TestModule"; | |
$dllName = "$moduleName.dll"; | |
$parentPath = [System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path); | |
$myDllPath = Join-Path $parentPath $dllName; | |
if (Test-Path $myDllPath) | |
{ | |
# get from current path. Normally always go this path | |
$path = $myDllPath; | |
} | |
else | |
{ | |
Write-Warning "Search Module" | |
# Stop Explorer at first hit | |
$moduleRoot = (Get-Module -ListAvailable -Name $moduleName | select -First 1).ModuleBase; | |
$path = Join-Path $moduleRoot $dllName; | |
} | |
# Import as DyanmicModule | |
$module = ImportModuleToCurrentAppDomain -Path $path |
Author
guitarrapc
commented
Dec 25, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment