我正在编写一个 PowerShell 脚本,该脚本需要在运行该脚本的计算机上安装特定的 PowerShell 模块。该模块提供了对于脚本正常工作至关重要的附加功能。
我想让我的脚本可移植,这样我就可以将我的脚本和模块放在一个文件夹中并将其复制到另一台机器上并直接运行它,而不需要手动安装。这可能吗?我尝试过在线搜索解决方案,但找不到任何专门解决我的问题的内容。
将模块目录(使用与已安装模块相同的目录结构)复制到脚本所在的子目录中。
\n例如,Pester模块的目录结构可能如下所示:
\n当PSGallery中提供该模块时,您也可以保存该模块而不先安装它。例如,将 PSGallery 中的 Pester 模块保存在如上所述的目录结构中:
\nmd Modules\nSave-Module -Name Pester -Path Modules\n
Run Code Online (Sandbox Code Playgroud)\n基本上有两种方法来加载模块。
\nImport-Module
,指定模块目录的完整路径,不带版本子目录。$env:PSModulePath
变量中。这使得仅使用模块名称和模块自动加载即可进行简单导入(就像实际安装了模块一样)。如果您的脚本被分成多个文件,这可能是首选。在这种情况下,您只需修改根脚本,根脚本加载的任何脚本都将自动使用可移植模块。使用示例Import-Module
:
# Import module from a sub directory relative to the current script\nImport-Module $PSScriptRoot\\Modules\\Pester\n\n# Now using functions from portable Pester module\nDescribe \'Portable Module Test\' {\n It \'Should have loaded portable module\' {\n $portableModuleFilePath = (Get-Item $PSScriptRoot\\Modules\\Pester\\*\\Pester.psm1).FullName\n (Get-Module Pester).Path | Should -Be $portableModuleFilePath \n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n使用示例$env:PSModulePath
:
# Insert portable module directory at the front of PSModulePath so our portable \n# version of the module will be preferred over any installed version.\n# This is only in script scope, the system environment variable won\'t be modified!\n$env:PSModulePath = "$PSScriptRoot\\modules;$env:PSModulePath"\n\n# Now using functions from portable Pester module, which PowerShell loads automatically.\nDescribe \'Portable Module Test\' {\n It \'Should have loaded portable module\' {\n $portableModuleFilePath = (Get-Item $PSScriptRoot\\Modules\\Pester\\*\\Pester.psm1).FullName\n (Get-Module Pester).Path | Should -Be $portableModuleFilePath \n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
1340 次 |
最近记录: |