如何将变量从模块传递回脚本?

时间:2016-09-17 14:02:55

标签: function powershell module

我注意到,在执行返回脚本后,模块函数内的变量不会保留在范围内。我遇到Export-ModuleMember,但似乎没有帮助,也许我错了。

FunctionLibrary.psm1

Function AuthorizeAPI
{
   # does a bunch of things to find $access_token
   $access_token = "aerh137heuar7fhes732"
}
Write-Host $access_token
aerh137heuar7fhes732

Export-ModuleMember -Variable access_token -Function AuthorizeAPI

主要脚本

Import-Module FunctionLibrary

AuthorizeAPI # call to module function to get access_token

Write-Host  $access_token 
# nothing returns

我知道作为替代方案,我可以点源一个单独的脚本,这将允许我获得access_token但我喜欢使用模块并在其中具有所有功能的想法。这可行吗?谢谢!

1 个答案:

答案 0 :(得分:1)

根据@ PetSerAl的评论,您可以更改变量的范围。阅读范围here。从控制台运行时,script范围对我不起作用; global做到了。

$global:access_token = "aerh137heuar7fhes732"

或者,您可以将函数返回值并存储在变量中;无需更改范围。

<强>功能

Function AuthorizeAPI
{
   # does a bunch of things to find $access_token
   $access_token = "aerh137heuar7fhes732"
   return $access_token
}

主脚本

Import-Module FunctionLibrary

$this_access_token = AuthorizeAPI # call to module function to get access_token

Write-Host  $this_access_token 
相关问题