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

gijlo24d  于 2023-03-02  发布在  Shell
关注(0)|答案(1)|浏览(125)

我正在处理一个PowerShell脚本,该脚本要求在运行脚本的计算机上安装特定PowerShell模块。此模块提供了对脚本正常工作至关重要的附加功能。
我想让我的脚本可以移植,这样我就可以把我的脚本和模块放在一个文件夹中,然后复制到另一台机器上,直接运行它,而不需要手动安装。这可能吗?我试着在线搜索解决方案,但我找不到任何可以解决我的问题的东西。

c9qzyr3d

c9qzyr3d1#

准备
将模块目录(使用与已安装模块相同的目录结构)复制到脚本所在的子目录中。
例如,Pester模块的目录结构可能如下所示:

  • 脚本目录
  • YourScript.ps1
  • 模块
  • 佩斯特
  • 5.4.0
  • pester.psm1
  • pester.psd1
  • ...

当模块在PSGallery中可用时,您也可以先保存模块而不安装它。例如,将Pester模块从PSGallery保存到上面的目录结构中:

md Modules
Save-Module -Name Pester -Path Modules

加载便携式模块

基本上有两种方法加载模块。
1.显式使用Import-Module,指定模块目录的完整路径,而不指定版本子目录。
1.隐式地将“Modules”路径插入到$env:PSModulePath变量中。这将启用仅使用模块名称的简单导入模块自动加载(就像模块实际安装了一样)。如果您的脚本被分割成多个文件,这可能是首选的。在这种情况下,您只需要修改根脚本,根脚本加载的任何脚本都将自动使用可移植模块。

使用Import-Module的示例:

# 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 
    }
}

相关问题