Zergatul
Zergatul

Reputation: 2010

Module scope gets duplicated for every script

I have a module, and script which runs simple user scripts. I want to keep user script as simple as possible, and that's why I use Import-Module with -Global flag. I have a problem with module "private" variable. In my case I have 2 copies of this variable. Can I achieve only one copy?

Below is simple example. You can run in by placing 3 files in the same folder and executing ScriptRunner.ps1.

Module.psm1

function Invoke-UserScript
{
    param($Path)

    $Script:UserScriptFailed = $false
    & $Path
    return $Script:UserScriptFailed
}

function New-Something
{
    $Script:UserScriptFailed = $true
}

function Write-Var
{
    Write-Host "Write-Var output: $Script:UserScriptFailed"
}

Export-ModuleMember -Function Invoke-UserScript
Export-ModuleMember -Function New-Something
Export-ModuleMember -Function Write-Var

ScriptRunner.ps1

Set-Location $PSScriptRoot
Import-Module -Name (Resolve-Path '.\Module.psm1') -Global
$failed = Invoke-UserScript -Path '.\UserScript.ps1'
Write-Output "ScriptRunner output: $failed"

UserScript.ps1

New-Something
Write-Var

In my example function New-Something sets UserScriptFailed to $true. But once UserScript.ps1 finishes, ScriptRunner.ps1 sees $false value.

Output:

Write-Var output: True
ScriptRunner output: False

Upvotes: 0

Views: 39

Answers (1)

Moerwald
Moerwald

Reputation: 11284

You could try to dot source the script you want to check:

function Invoke-UserScript
{
    param($Path)

    $Script:UserScriptFailed = $false
    # Sourcing may add the functions to the current scope
    . $Path
    & $Path
    return $Script:UserScriptFailed
}

Upvotes: 1

Related Questions