Created
July 19, 2023 18:20
-
-
Save romero126/1846521f578716397c7e06220b7f679b to your computer and use it in GitHub Desktop.
Import-Module Manually
This file contains hidden or 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
function Import-ModuleManually { | |
param( | |
[Parameter(Mandatory=$true)] | |
[string]$Module, | |
[Parameter(Mandatory=$false)] | |
[switch]$Force | |
) | |
$moduleExists = Get-Module -Name $Module -All | |
if ($moduleExists) { | |
if (-not $Force) { | |
throw "The Module '$($moduleExists.Name)' is already is loaded" | |
} | |
else { | |
Remove-Module -Name $Module -Force | |
} | |
} | |
# Look for the module in the $env:PSModulePath | |
$items = $env:PSModulePath -split ";" | |
foreach ($item in $items) | |
{ | |
$moduleFile = Get-Item -Path "$item\$Module\$Module.psm1" -ErrorAction SilentlyContinue | |
if ($moduleFile) { | |
Write-Host "ModuleFile is", $moduleFile.FullName | |
# Now I want to import the file as an AST Parsed scriptblock and import it as a module | |
$_loadModule_errors = $null | |
$_loadModule_tokens = $null | |
$_loadModule_ast = [System.Management.Automation.Language.Parser]::ParseFile($moduleFile.FullName, [ref] $_loadModule_tokens, [ref] $_loadModule_errors) | |
if ($_loadModule_errors) { | |
throw $_loadModule_errors | |
} | |
Write-Host "VerbosePreference $VerbosePreference" | |
$_scriptblock = $_loadModule_ast.GetScriptBlock() | |
$_moduleInfo = Import-PowerShellDataFile -Path "$($moduleFile.DirectoryName)\$($moduleFile.BaseName).psd1" | |
$_module = New-Module -Name $moduleFile.BaseName -ScriptBlock $_scriptblock @_moduleInfo -Verbose:$VerbosePreference | |
## Import psd1 info into the module | |
$_module.PrivateData = $_moduleInfo.PrivateData | |
# use Reflection to set $_module version | |
try { | |
$_type = $_module.GetType() | |
$_type.InvokeMember("SetVersion", "InvokeMethod,NonPublic,Instance", $null, $_module, ([System.Version]$_moduleInfo.ModuleVersion)) | |
} | |
catch { | |
} | |
$_module | Import-Module -Force #-Verbose:$VerbosePreference | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment