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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/Windows/...', 1758778324, '216.73.216.41', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/Windows/PowerShell/language/operator/call/access-module-private-variables(66): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78