gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:34:11 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com