我有一个脚本,它导入一个模块并运行该模块中的一个函数。 我的问题是能够访问模块函数中设置的变量的值。 IE。使在模块内的函数中声明的变量可供调用脚本使用。
模块中我的函数中的代码是:
Function TestFunction
{
$Script:setVarReturn = "Hello"
Write-Host ("Value of setVarReturn inside module function is " + $setVarReturn)
}
调用该模块函数的脚本是:
Import-Module -Name 'E:\Data\Computing\Software\Programming\Scripts\dev\DS_ModMisc_dev.psm1'
Clear-Host
TestFunction
Write-Host ("Value of setVarReturn inside script is " + $setVarReturn)
我得到的结果是:
如您所见,脚本将变量视为 null。
正如你所看到的,我在绝望中,即使我知道它不会有任何区别,给定变量的脚本范围 这似乎是一个简单的请求,有人可以推荐一个简单的解决方案吗?
最佳答案
我看到您拥有的选项是将变量设置为 $global:
作用域而不是 $script:
,以便该变量对所有作用域都可见(包括调用者):
New-Module -Name tempModule1 -ScriptBlock {
function TestFunction {
$global:setVarReturn = 'Hello'
Write-Host ('Value of setVarReturn inside module function is ' + $setVarReturn)
}
} | Import-Module
# Call the function
tempModule1\TestFunction
# Check variable, should output `Hello`
$setVarReturn
# Cleanup temp module and variable
Remove-Module tempModule1
Remove-Variable setVarReturn
或者使用您现在拥有的 $script:
作用域,它将变量设置在模块的作用域中,但调用者看不到它,然后您可以通过访问模块的作用域来检索该变量范围:
New-Module -Name tempModule2 -ScriptBlock {
function TestFunction {
$script:setVarReturn = 'Hello'
Write-Host ('Value of setVarReturn inside module function is ' + $setVarReturn)
}
} | Import-Module
# Call the function
tempModule2\TestFunction
# Check variable in the Module's scope, should output `Hello`
& (Get-Module tempModule2) { $setVarReturn }
# Cleanup temp module and variable
Remove-Module tempModule2
Remove-Variable setVarReturn
或者,将其设置为环境变量 ($env:
):
New-Module -Name tempModule3 -ScriptBlock {
function TestFunction {
$env:setVarReturn = 'Hello'
Write-Host ('Value of setVarReturn inside module function is ' + $env:setVarReturn)
}
} | Import-Module
# Call the function
tempModule3\TestFunction
# Check the env var
$env:setVarReturn
# Cleanup temp module and env variable
Remove-Module tempModule3
Remove-Item env:setVarReturn
对于选项 1 和 3,您应该注意,您正在更改调用者的 session 状态,并且这样做不是最常见的做法,换句话说,您应该有一个非常具体的需要这样做,或者考虑是否存在更好的方式来做你正在寻找的事情。更多相关文档可以在 about Scopes 中找到。和 about Environment Variables .
也许是使用模块变量并使用 Export-ModuleMember
导出它的另一个选项:
New-Module -Name tempModule4 -ScriptBlock {
$myRefVar = ''
function TestFunction {
([ref] $myRefVar).Value = 'Hello'
Write-Host ('Value of myRefVar inside module function is ' + $myRefVar)
}
Export-ModuleMember -Variable myRefvar -Function TestFunction
} | Import-Module
# Check empty var
$myRefVar
# Call the function
tempModule4\TestFunction
# Check var again, should be `Hello`
$myRefVar
# We can see the Module variable here
(Get-Module tempModule4).ExportedVariables
# Cleanup temp module
Remove-Module tempModule4
关于PowerShell - 如何使在模块内的函数中声明的变量可供调用脚本使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76093823/