PowerShell 模块 - 在哪里存储自定义构建的模块以及如何使用配置文件导入它们。ps1

PowerShell Modules - Where to store custom built modules and how to import them using profile.ps1

我对在哪里存储我的自定义 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: 驱动器中不存在该目录的路径。

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

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

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 下的所有库,因此添加新库将始终自动完成。