Powershell加载模块内部的模块[范围]

时间:2018-06-15 11:13:24

标签: powershell module scope powershell-v4.0

解决方案:

Import-Module (Join-Path $PSScriptRoot $_.FileName) -Verbose -Global

在我的模块中添加-Global开关,使所有函数都可以在它自己的上下文之外访问。

我有一个我创建的Powershell模块(ConfigModule.psm1),我曾经使用过config.xml

每当我将模块包含在测试脚本中时,一切正常。

我调用名为Import-ConfigModules的函数并导入(type="Module")的模块,并从type="script"创建XML的变量,其值为{{1} }}

所以这是我的加载层次结构:

  1. 测试脚本导入Get-Item...
  2. ConfigModule.psm1导入同一目录中的其他模块
  3. 其他模块具有不同的功能。
  4. 问题:

    在不同文件中调用模块函数时,模块会加载,因为我使用ConfigModule.psm1切换到测试,我可以访问变量,但是我无法访问函数-Verbose 即可。

    这是导入模块范围问题吗?

    如果是这样,如何将模块传递到我的测试脚本上下文中?

    <小时/> ConfigModule.psm1&gt;进口ConfigModules

    not recognized

    以下是Function Import-ConfigModules { param([String]$Path) $modules = Get-ConfigModules -Path $Path # Iterate by FileType $modules.Keys | % { switch($modules[$_]) { {$_.FileType -eq "module"} { # If Module exists, load, else find similar modules= if(Test-Path (Join-Path $PSScriptRoot $_.FileName)) { Import-Module (Join-Path $PSScriptRoot $_.FileName) -Verbose # Test if module was loaded if(Get-Module $_.VariableName) { Write-Host "Module [Loaded]: " ($_.FileName) -ForegroundColor Green } else { Write-Host "Module [Error]: Could not import module - " ($_.FileName) -ForegroundColor Green } } else { Write-Host "Module [Missing]: $($_.FileName).`r`nFound similar: " -ForegroundColor Yellow -NoNewline Get-SimilarFile ` -Path $PSScriptRoot ` -Name $_.FileName } break } {$_.FileType -eq "script"} { if(Test-Path (Join-Path $PSScriptRoot $_.FileName)) { Write-Host "Script [Loaded]: " ($_.FileName) -ForegroundColor Green # Create variables dynamically Set-Variable -Name "$($_.VariableName)" -Scope Global -Value (Get-Item -Path (Join-Path $PSScriptRoot $_.FileName)) } else { Write-Host "Script [Missing]: $($_.FileName).`r`nFound similar: " -ForegroundColor Yellow -NoNewline Get-SimilarFile ` -Path $PSScriptRoot ` -Name $_.FileName } break } default { Write-Warning "$($_.FileName) : Bad FileType definition. {FileType: $($_.FileType)}" } } Write-Host } } 的示例:

    Config.xml

1 个答案:

答案 0 :(得分:1)

有效的解决方案:

Import-Module (Join-Path $PSScriptRoot $_.FileName) -Verbose -Global

通过将-Global切换添加到Import-Module cmdlet,它会将模块导入全局范围,允许外部脚本访问其功能。

相关问题