使 PowerShell 脚本及其依赖项可移植

Faj*_*iya 5 powershell module

我正在编写一个 PowerShell 脚本,该脚本需要在运行该脚本的计算机上安装特定的 PowerShell 模块。该模块提供了对于脚本正常工作至关重要的附加功能。

我想让我的脚本可移植,这样我就可以将我的脚本和模块放在一个文件夹中并将其复制到另一台机器上并直接运行它,而不需要手动安装。这可能吗?我尝试过在线搜索解决方案,但找不到任何专门解决我的问题的内容。

zet*_*t42 7

准备工作

\n

将模块目录(使用与已安装模块相同的目录结构)复制到脚本所在的子目录中。

\n

例如,Pester模块的目录结构可能如下所示:

\n
    \n
  • 脚本目录\n
      \n
    • 你的脚本.ps1
    • \n
    • 模块\n
        \n
      • 纠缠\n
          \n
        • 5.4.0\n
            \n
          • 纠缠者.psm1
          • \n
          • 纠缠.psd1
          • \n
          • \xe2\x80\xa6
          • \n
          \n
        • \n
        \n
      • \n
      \n
    • \n
    \n
  • \n
\n

当PSGallery中提供该模块时,您也可以保存该模块而不先安装它。例如,将 PSGallery 中的 Pester 模块保存在如上所述的目录结构中:

\n
md Modules\nSave-Module -Name Pester -Path Modules\n
Run Code Online (Sandbox Code Playgroud)\n

加载便携式模块

\n

基本上有两种方法来加载模块。

\n
    \n
  1. 显式使用Import-Module,指定模块目录的完整路径,不带版本子目录。
  2. \n
  3. 通过将“模块”路径隐式插入$env:PSModulePath变量中。这使得仅使用模块名称和模块自动加载即可进行简单导入(就像实际安装了模块一样)。如果您的脚本被分成多个文件,这可能是首选。在这种情况下,您只需修改根脚本,根脚本加载的任何脚本都将自动使用可移植模块。
  4. \n
\n

使用示例Import-Module

\n
# 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

\n
# 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