Peering into script modules

PowerShell Team

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}
PS>& $m {$script:foo = 'NewFoo'}
PS>& $m {$foo}

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



Nigel Sharples [MSFT]


Discussion is closed.

Feedback usabilla icon