Home > database >  Access a variable from parent scope
Access a variable from parent scope

Time:05-26

In Single Module Scenario: Running Set-Var returns 10.

# m.psm1

function Set-Var {
    $MyVar = 10
    Get-Var
}

function Get-Var {
    $MyVar
}

In Nested Modules Scenario: Running Set-Var does not return any value.

# m1.psm1

function Get-Var {
    $MyVar
}
# m.psm1

Import-Module .\m1.psm1

function Set-Var {
    $MyVar = 10
    Get-Var
}

How do I achieve the same effect as a single module with nested modules? Using $script:MyVar also does not work. However, I would like to keep the scope of the variable local to enable concurrent executions with different values.

CodePudding user response:

Your code doesn't work because local variables are not inherited by functions in nested module context.

You can do this instead:

function Get-Var {
    [CmdletBinding()] param()
    $PSCmdlet.SessionState.PSVariable.Get('MyVar').Value
}
  • Use the CmdletBinding attribute to create an advanced function. This is a prerequisite to use the automatic $PSCmdlet variable, which we need in the next step.
  • Use its SessionState.PSVariable member to get or set a variable from the parent (module) scope.
  • Note this works only when the caller is in a different module or script.
  • This answer shows an example how to set a variable in the parent (module) scope.
  • See also: Is there any way for a powershell module to get at its caller's scope?
  • Related