Search notes:

PowerShell: access module-private variables with the call operator

The call operator & allows to access variables that are private to a module with the following syntax:
& $moduleInfo { … }
$moduleInfo is an instance of System.Management.Automation.PSModuleInfo (which can be obtained, for example, with get-module) and { … } is a script block (which is executed in the module's «context»).
This is demonstrated with the following simple example. First, we need a module (mdl.psm1) with a private variable $private_variable:
set-strictMode -version latest

[int] $private_variable = 40

function incVar {
   $script:private_variable++
   write-host "var = $script:private_variable"
}

function decVar {
   $script:private_variable
   write-host "var = $script:private_variable"
}
Github repository about-PowerShell, path: /language/operator/call/mdl.psm1
Then, we load the module into the current session (import-module ./mdl.psm1), use the functions incVar and decVar to modify the value of the internal variable and then print its value with the mentioned syntax:
set-strictMode -version latest

import-module ./mdl.psm1

incVar
incVar
incVar
decVar

& (get-module mdl) { write-host "value of variable is $private_variable" }
Github repository about-PowerShell, path: /language/operator/call/access-module-variable.ps1

Index