Home > database >  How do I get a variable from a module run space in PowerShell?
How do I get a variable from a module run space in PowerShell?

Time:10-07

There is a module that has an "initialize" function that sets a variable that gets used in other scripts/functions in the module to validate that the initialize function was run. Something like

Start-InitializeThing
Connect to the API
    
$Script:SNOWinit = $true

Then in another script/function it will check:

if ($Script:SNOWinit -eq $true) { Do the thing!}

Is there a way to grab that $Script:SNOWinit in the same PowerShell window, but not the same module?

I want to run the same check but for a different function that is not in the module.

Can I do this, can I "dig" into like the modules runspace and check that variable. I don't have the means to edit the functions in the module so I cant change what type of variable is set once the initialize script has run.

CodePudding user response:

Assuming that the module of interest is named foo and that it has already been imported (loaded):

. (Get-Module foo) { $SNOWinit }

If you want to import the module on demand:

. (Import-Module -PassThru foo) { $SNOWinit }
  • The above returns the value of the $SNOWinit variable defined in the root scope of module foo.

  • Note that it is generally not advisable to use this technique, because it violates the intended encapsulation that modules provide. In the case at hand, $SNOWinit, as a non-public module variable, should be considered an implementation detail, which is why you shouldn't rely on its presence in production code.

CodePudding user response:

From the bible, WPiA. More mysterious uses for the call operator.

# get a variable in module scope
$m = get-module counter
& $m Get-Variable count
& $m Set-Variable count 33
  • Related