Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active February 8, 2016 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/72bffd1e1c12bec100f9 to your computer and use it in GitHub Desktop.
Save guitarrapc/72bffd1e1c12bec100f9 to your computer and use it in GitHub Desktop.
Assembly.Load() then Import-Module as DynamicModule
# 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
@guitarrapc
Copy link
Author

animation

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