Powershell: add variable modifier $module:

Created on 18 Jan 2020  路  4Comments  路  Source: PowerShell/PowerShell

$module:var display variable 'var' in module we can use The ExecutionContext variable to display 'var' variable but modifier $module: is better

step to reproduce:

$m = new-module {
  $var = 'in module'
} | ipmo -force -PassThru

$var = 'in script'

$sb={
 $var = 'in scriptblock'
 Write-Host $local:var 
 Write-Host $script:var 
 Write-Host $module:var
}

&$sb 

===output===

in scriptblock
in script
in module
Issue-Enhancement

Most helpful comment

There's generally no reason to access a module's _non-exported_ variables - a module's non-exported variables should be considered private.

If really needed, you can already access such variables, and I think that mechanism is sufficient, given how exceptional the use case is (tip of the hat to @SeeminglyScience's blog post):

PS> & $m { $var }
in module

All 4 comments

@p0W3RH311 how will we determine _which_ module to pull a variable from? There could be any number of modules loaded at a given time. Searching through all of them would take quite some time, I'd imagine. Also, how would you handle having multiple modules loaded which each have a variable by the same name?

@p0W3RH311 how will we determine _which_ module to pull a variable from? There could be any number of modules loaded at a given time. Searching through all of them would take quite some time, I'd imagine. Also, how would you handle having multiple modules loaded which each have a variable by the same name?

we can use this syntax for example

Write-Host $module:nameofmodule:var

In that instance, how would you expect $module:nameofmodule to behave?

There's generally no reason to access a module's _non-exported_ variables - a module's non-exported variables should be considered private.

If really needed, you can already access such variables, and I think that mechanism is sufficient, given how exceptional the use case is (tip of the hat to @SeeminglyScience's blog post):

PS> & $m { $var }
in module
Was this page helpful?
0 / 5 - 0 ratings