我有一个脚本,它导入一个模块并在模块中运行一个函数。 我的问题是能够访问模块函数中变量集的值。 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,您应该注意,您正在改变呼叫者的会话状态,这样做并不是最常见的做法,换句话说,您应该有非常具体的需要这样做,或者考虑是否有更好的方法做你正在寻找的东西。也可以在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