我意识到“输出变量”可能不是正确的术语,这就是为什么我的谷歌搜索失败了。我猜想它围绕着显式设置变量范围,但我尝试阅读关于作用域文档,但它对我来说并不直观。
本质上,我正在尝试实现与Invoke-RestMethod中的
如果我要包装一个已有的函数,并且想有效地将输出变量名传递,那么事情如何改变(如果有的话)?
本质上,我正在尝试实现与Invoke-RestMethod中的
-SessionVariable
参数相当的功能,即在自己模块的函数中使用一个字符串参数,该参数会变成调用者范围内的变量。function MyTest
{
param([string]$outvar)
# caller scoped variable magic goes here
set-variable -Name $outvar -value "hello world"
# normal function output to pipeline here
Write-Output "my return value"
}
# calling the function initially outputs "my return value"
MyTest -outvar myvar
# referencing the variable outputs "hello world"
$myvar
如果我要包装一个已有的函数,并且想有效地将输出变量名传递,那么事情如何改变(如果有的话)?
function MyWrapper
{
param([string]$SessionVariable)
Invoke-RestMethod -Uri "http://myhost" -SessionVariable $SessionVariable
# caller scoped variable magic goes here
set-variable -Name $SessionVariable -value $SessionVariable
}
# calling the wrapper outputs the normal results from Invoke-RestMethod
MyWrapper -SessionVariable myvar
# calling the variable outputs the WebRequestSession object from the inner Invoke-RestMethod call
$myvar
顺便说一句,如果有关系的话,我正在努力使模块与Powershell v3+兼容。
Set-Variable -Scope 1
将无法正常工作。模块使用单独的SessionState
和单独的作用域层次结构,因此“直接父级”将不是调用者。 - user4003407-Scope 2
很可能是指全局作用域,而不是调用者的作用域(除非它们相同)。是的,这是因为你在模块中。 - user4003407