Peering into script modules

Peering into script modules

  • Comments 1

Sometimes it’s handy to access internal elements of script modules. For instance you may be using a 3rd party module in your application and would like to see the internal state for debugging purposes.

This can be accomplished with the invoke operator (&) which allows you to access a modules session state:

& $module {script block}

The script block is executed in the context of the module.

Create a script module that exports nothing:

[string] $foo = "IamFoo"

function Hidden($zarg) {
"$zarg was passed to me"
}

Export-ModuleMember -Function @()


Save to a file ‘NoExport.psm1’, import the module and assign to a variable:

PS> $m = import-module .\NoExport.psm1 -passthru

If we try to call function ‘Hidden’ we get an error because it was not exported, but we can call it with the operator & .
 
PS>& $m {Hidden 'bar'}
bar was passed to me

Likewise, we can also retrieve and set the module variable $foo:

PS>& $m {$foo}
IamFoo
PS>& $m {$script:foo = 'NewFoo'}
PS>& $m {$foo}
NewFoo

Note that in order to set variable foo you must use script scope.

 

Cheers,

Nigel Sharples [MSFT]

Leave a Comment
  • Please add 1 and 5 and type the answer here:
  • Post
  • Why is it required to use script scope when setting the value of $foo and not when getting it... its inconsistent and confusing.

    And the script scope is confusing too.. can't there be a module scope?

Page 1 of 1 (1 items)