0

Is it possible to set a value of a variable with the script scope from a module (.psm1 file)? The following does not work because, from what I've read, script scope in a module is not really a script scope.

TestScope.psm1

function Initialize-TestVariable {
param (
    [string]
    $Name
)
    $scope      = "Script"
    $visibility = "Public"

    Set-Variable -Scope $scope -Name $Name -Value "Set in module" -Force -Visibility $visibility
}

Export-ModuleMember -Function *

TestScope.ps1

param (
    [string]
    $Value = "Default value"
)

$path = Join-Path (Split-Path -Path $PSCommandPath -Parent) 'TestScope.psm1'
Import-Module $path -ErrorAction Stop

Initialize-TestVariable -Name "Value"

$Value

Output

Default value

I need output to be:

Set in module

If anyone wonders why I need this, there is a valid reason (so I'm not interested in the discussion whether this is a good idea, just need to know if this can be done, and, if so, how). Also, using the global scope is not an option, since it changes the state (there will be hanging global variables after the script exits that were not there when the script started).

1 Answer 1

1

I figured it out:

TestScope.psm1

function Initialize-TestVariable {
    [CmdletBinding()]
    param (
        [string]
        $Name
    )

    $PSCmdlet.SessionState.PSVariable.Set($Name, "Set in module")
}

Export-ModuleMember -Function *
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.