2

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Erick W
  • 25
  • 4

2 Answers2

3

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    This is awesome! Thank you so much. That blog post was a good read. I appreciate the note on best practice too. I will reach out to the people that do own the module and see if we can update the way we create the variable. – Erick W Oct 06 '21 at 22:09
0

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
js2010
  • 23,033
  • 6
  • 64
  • 66