【问题标题】:How to include functions in script files into PowerShell module如何将脚本文件中的函数包含到 PowerShell 模块中
【发布时间】:2016-11-07 03:55:41
【问题描述】:

我正在使用 PowerShell 5.0 并尝试编写多文件模块。
模块的文件夹结构如下所示:

/FooModule
--- FooModule.psd1
--- FooModule.psm1
--- AnotherScriptFile.ps1

清单文件 FooModule.psd1 自定义如下:

@{
    ModuleVersion = '0.0.1'
    GUID = ...
    Author = ...
    CompanyName = ..
    Copyright = ...
    Description = ...
    PowerShellVersion = '5.0'
    ClrVersion = '4.0'
    RootModule = "FooModule.psm1"
    FunctionsToExport = '*'
    CmdletsToExport = '*'
    VariablesToExport = '*'
    AliasesToExport = '*'
    # HelpInfoURI = ''
    # DefaultCommandPrefix = ''
}

我把这些放在FooModule.psm1的开头:

Push-Location $PSScriptRoot
.\AnotherScriptFile.ps1
Pop-Location

AnotherScriptFile.ps1 如下所示:

Write-Host "Imported!"
function Get-FooFunction($val)
{
    return "Foo Bar";
}

我认为,当我导入模块时,它会将 AnotherScriptFile.ps1 的函数和变量读取到模块的范围内,然后导出。 可悲的是,在我在模块文件夹中使用Import-Module .\FooModule.psm1 导入模块后,调用Get-FooFunction 给了我一个错误,说Get-FooFunction 不存在,'Write-Host "Imported!" 被调用了。

完成这项工作的正确方法是什么?

【问题讨论】:

    标签: powershell powershell-module


    【解决方案1】:

    您可以在模块清单中的 ScriptsToProcess 数组中添加脚本:

    # Script files (.ps1) that are run in the caller's environment prior to importing this module.
    ScriptsToProcess = @('.\AnotherScriptFile.ps1')
    

    【讨论】:

    • 感谢您的快速回复。我试过了,但是没有用:(
    • 另一种方法是在您的FooModule.psm1 中点源文件(带有另一个点)。试试这个:. .\AnotherScriptFile.ps1
    • 我试过了,但这一次发生了错误,说..\AnotherScriptFile.ps1 is not recognized as the name of a cmdlet, function,script file, or operable program.。工作目录设置为模块的根目录。
    • 对不起,由于换行,我没有看到dot operator.和文件路径.\AnotherScriptFile.ps1之间的空格。我将 FooModule.psm1 的第二行更改为 -> .[space].\AnotherScriptFile.ps1,一切正常!非常感谢!
    • 知道为什么 ScriptsToProcess 不起作用吗?是不是无法将函数定义加载到环境中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2017-11-04
    • 1970-01-01
    • 2010-09-28
    • 2019-09-13
    相关资源
    最近更新 更多