AndrewZtrhgf
AndrewZtrhgf

Reputation: 29

Is it possible to force functions from one module to honor read-only setting on variables from different module?

Hi imagine this situation. You have 2 powershell modules as defined bellow. If you import them to console (just run the code in console), you will be able to use variable test, but not modify it (expected behaviour). But function changeVariable from second module doesnt honor the read only settings and internally can do whatever it wants with variable test.

first module:

New-Module {
New-Variable test -Value "test" -Option AllScope, Constant -Force -Scope global

Export-ModuleMember -Variable *
}

second module:

New-Module {
function changeVariable {
    $test = "someString" # this should end with error, that variable cannot be changed 
    $test
}

Export-ModuleMember -Function *
}

So is it possible to create globally non-modifiable variables in powershell?

Upvotes: 0

Views: 32

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25011

The second module is not accessing the $test variable from the global scope. It is accessing a variable from the function's scope. You need to indicate that it is a global variable. One way to do this is with the global scope modifier.

New-Module {
function changeVariable {
    $global:test = "someString" # this should end with error, that variable cannot be changed 
    $global:test
}

Export-ModuleMember -Function *

}

There are other scopes available that can be used with the $[<scope-modifier>:]<name> = <value> syntax. See About Scopes.

Upvotes: 1

Related Questions