0

I have noticed that variables inside a module function do not remain in scope after execution returns to the script. I came across Export-ModuleMember but that didn't seem to help, perhaps i'm using it wrong.

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

Main script

Import-Module FunctionLibrary

AuthorizeAPI # call to module function to get access_token

Write-Host  $access_token 
# nothing returns

I know as an alternative I could just dot source a separate script and that would allow me to get the access_token but I like the idea of using modules and having all my functions therein. Is this doable? Thanks SO!

6
  • $access_token = -> $script:access_token = Commented Sep 17, 2016 at 14:10
  • Hm, that didnt work. Variable is still empty when execution returns to Main script Commented Sep 17, 2016 at 14:18
  • Variable empty or not exists? Commented Sep 17, 2016 at 14:19
  • How do I tell the difference? Commented Sep 17, 2016 at 14:20
  • I also notice the module doesn't seem to execute the Export-ModuleMember line. After the function has finished it just returns to the main script Commented Sep 17, 2016 at 14:21

1 Answer 1

1

As per @PetSerAl's comment, you can change the scope of your variable. Read up on scopes here. script scope did not work for me when running from console; global did.

$global:access_token = "aerh137heuar7fhes732"

Alternatively, you can return the value form the function it and store in a variable; no scope change needed.

Function

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

Main Script

Import-Module FunctionLibrary

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

Write-Host  $this_access_token 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.