# Import module from a sub directory relative to the current script
Import-Module $PSScriptRoot\Modules\Pester
# Now using functions from portable Pester module
Describe 'Portable Module Test' {
It 'Should have loaded portable module' {
$portableModuleFilePath = (Get-Item $PSScriptRoot\Modules\Pester\*\Pester.psm1).FullName
(Get-Module Pester).Path | Should -Be $portableModuleFilePath
}
}
使用$env:PSModulePath的示例:
# Insert portable module directory at the front of PSModulePath so our portable
# version of the module will be preferred over any installed version.
# This is only in script scope, the system environment variable won't be modified!
$env:PSModulePath = "$PSScriptRoot\modules;$env:PSModulePath"
# Now using functions from portable Pester module, which PowerShell loads automatically.
Describe 'Portable Module Test' {
It 'Should have loaded portable module' {
$portableModuleFilePath = (Get-Item $PSScriptRoot\Modules\Pester\*\Pester.psm1).FullName
(Get-Module Pester).Path | Should -Be $portableModuleFilePath
}
}
1条答案
按热度按时间c9qzyr3d1#
准备
将模块目录(使用与已安装模块相同的目录结构)复制到脚本所在的子目录中。
例如,Pester模块的目录结构可能如下所示:
当模块在PSGallery中可用时,您也可以先保存模块而不安装它。例如,将Pester模块从PSGallery保存到上面的目录结构中:
加载便携式模块
基本上有两种方法加载模块。
1.显式使用
Import-Module
,指定模块目录的完整路径,而不指定版本子目录。1.隐式地将“Modules”路径插入到
$env:PSModulePath
变量中。这将启用仅使用模块名称的简单导入和模块自动加载(就像模块实际安装了一样)。如果您的脚本被分割成多个文件,这可能是首选的。在这种情况下,您只需要修改根脚本,根脚本加载的任何脚本都将自动使用可移植模块。使用
Import-Module
的示例:使用
$env:PSModulePath
的示例: