【问题标题】:PowerShell Modules - Where to store custom built modules and how to import them using profile.ps1PowerShell 模块 - 存储自定义构建模块的位置以及如何使用 profile.ps1 导入它们
【发布时间】:2018-08-15 19:40:10
【问题描述】:

我对存储自定义 Powershell 模块的位置有点困惑。

这是我的Utility.psm1的一个例子

New-Module -Name 'Utility' -ScriptBlock {
    function New-File($filename)
    {
        if(-not [String]::IsNullOrEmpty($filename))
        {
            New-Item -ItemType File "$filename"
        } else {
            Write-Error "function touch requires filename as a parameter"
        }
    }

    function Change-DirectoryUp($number)
    {
        for($i=0; $i -lt $number; $i++)
        {
            if((pwd).Path -eq 'C:\') { break } else { cd .. }
        }
    }

    function Get-EnabledWindowsFeatures()
    {
        $features = Get-WindowsOptionalFeature -Online
        $features | ? {$_.State -eq 'Enabled'} | select FeatureName
    }
}

如果我想在每次打开 Powershell 或 Powershell ISE 时都导入这个模块,我该怎么做?我将Utility.ps1 存储在哪里重要吗?我想避免将完整路径传递给这个文件......但我担心使用相对路径会依赖于“Start-In”路径。

我注意到有一个名为 $env:PSModulePath 的变量,但我的 C: 驱动器中不存在该目录的路径。

我应该创建那个目录并将它们存储在那里吗?如果我这样做,如何导入模块?

【问题讨论】:

  • 如果您总是希望它加载到您的会话中,请使用配置文件。
  • @TheIncorrigible1 如果我将所有的代码都放入我的个人资料中,它会变得非常混乱。我希望使用配置文件作为对某些代码和抽象进行分组的一种方式
  • 这并不能否定我的说法......只需编写一个带有函数的脚本并将其点源到您的配置文件中,或者如果您愿意,可以从中创建一个模块并使用Import-Module
  • @TheIncorrigible1 点源文件与在New-Module 中包装后运行Import-Module 之间有什么区别吗?....我还是想不通
  • 仅当您的文件正在加载二进制文件、运行前置条件脚本、依赖版本控制等时。如果它只是一个带有 psm1 扩展名的静态脚本,不妨点源它。

标签: powershell powershell-5.0 powershell-ise import-module


【解决方案1】:

我的解决方案是为我的所有 psm1 模块和我的脚本保留一个库文件夹,并在我每次编写新脚本时重用它。您可以为此使用 $myInvocation 变量,因为它与您正在运行的脚本文件所在的位置相关。我所做的是具有以下结构:

C:\Your\Path\To\Script\YourScript.ps1
C:\Your\Path\To\Script\Libraries\allYourPsmModules.psm1

我有一个名为 Import-Libraries.psm1 的模块,它存储在 Libraries 文件夹下,包含以下代码:

Function Global:Import-Libraries {    
param (
    [string] $LibrariesPath
)    
foreach ($module in (Get-ChildItem -Path "$LibrariesPath./*.psm1" -File)) {
    Import-Module ($module).FullName -Force
    }
}

您的脚本需要从以下内容开始:

$scriptDir = (split-path -parent -path $MyInvocation.MyCommand.Path)
Import-module $scriptDir\Libraries\Import-Libraries.psm1
Import-Libraries .\Libraries

这三行的作用是 $scriptDir 成为一个相对路径,因此您将脚本存储在哪里并不重要。然后我导入名为“Import-Modules”的模块,然后在 Libraries 文件夹中运行该模块。名为 Import-Libraries 的模块将始终导入我在文件夹 Libraries 下的所有库,因此添加新库将始终自动完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多