powershell - 在 psake 任务中使用时在模块中定义的功能范围

标签 powershell psake

我有一个 psake 任务,如下所示(为清楚起见,已简化):

Task Invoke-Deploy {

    Import-Module "somefunctions.psm1"

    Import-Module "morefunctions.psm1"

    Set-Something #This is a function defined in morefunctions.psm1
}

函数 Set-Something(在模块 morefunctions.psm1 中定义)尝试调用函数 Get-Something(在 somefunctions.psm1 中定义)。当它发生时,我得到一个错误:

The term 'Get-Something' is not recognized as the name of a cmdlet, function, script file, or operable program.



有趣的是,我将“morefunctions.psm1”修改为“Import-Module”somefunctions.psm1”,此时一切正常。但是,我宁愿不必这样做,因为我希望我的模块是“松散耦合”的,因为它们不需要依赖其他模块的存在。

我对 Powershell 中的函数/变量范围的了解有限,但我认为两个不同导入模块中的函数位于同一范围内,因此其中一个模块中的函数将能够调用另一个模块中的函数。

我怀疑该范围受到我在 psake 任务中这一事实的影响,我希望这里的人可以确认这一点,并建议我应该如何解决这个问题。 TIA。

最佳答案

我创建了一个脚本模块 test-module.psm1:

function Invoke-Test {
    Import-Module ".\somefunctions.psm1"

    Import-Module ".\morefunctions.psm1"

    Set-Something #This is a function defined in morefunctions.psm1
}

和几个虚拟模块 somefunctions.psm1:
function Get-Something {
    'Get-Something'
}

和更多functions.psm1:
function Set-Something {
    Get-Something
    'Set-Something'
}

如果我打电话
Import-Module .\test-module.psm1
Invoke-Test

然后我收到错误“Get-Something:‘Get-Something’一词不是
识别为 cmdlet、函数、脚本文件或可操作的名称
程序。”。所以它看起来像一个处理脚本的通用 PowerShell 问题
模块。我尝试了 PowerShell v2.0、v3.0 和 v4.0。

如果没有变通方法,这可能无法在 psake 中解决,因为它是一个脚本
模块。您可以使用类似的工具
Invoke-Build .它被实现
作为脚本并避免此类问题。它工作正常
使用此构建脚本:
Task Invoke-Deploy {

    Import-Module ".\somefunctions.psm1"

    Import-Module ".\morefunctions.psm1"

    Set-Something #This is a function defined in morefunctions.psm1
}

它按预期输出:
Build Invoke-Deploy ...\.build.ps1
Task /Invoke-Deploy
Get-Something
Set-Something
Done /Invoke-Deploy 00:00:00.0150008
Build succeeded. 1 tasks, 0 errors, 0 warnings 00:00:00.1450083

关于powershell - 在 psake 任务中使用时在模块中定义的功能范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033346/

相关文章:

powershell - 我不知道为什么找不到该小组的成员

variables - 在Powershell中评估变量中的变量

powershell - 将 Dos 命令转换为 Powershell 命令

powershell - TeamCity 不使用 powershell 显示服务消息

asp.net-mvc - 由 TeamCity 触发的构建步骤始终会构建 - 即使没有任何更改

sql - Powershell : error report while Import CSV file to SQL server

powershell - 显示变量的名称和输出?

c# - Powershell Cmdlet 缺少程序集 Google Api

entity-framework - 如何从 psake 构建运行代码优先迁移?

powershell - psake报错