2016-09-17 34 views
0

我已經注意到,模塊函數內的變量在執行返回到腳本後不會保留在範圍內。我遇到了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,但我喜歡這個主意使用模塊並具有我所有的功能。這是可行的嗎?謝謝!

+0

'$ =的access_token' - >'$腳本:ACCESS_TOKEN =' – PetSerAl

+0

嗯,沒有工作。當執行返回到主腳本時,變量仍然爲空 – Quanda

+0

變量爲空還是不存在? – PetSerAl

回答

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 
+0

$全球範圍爲我工作,謝謝! – Quanda