Setting a static member from dot-sourced file

33 Views Asked by At

While getting the value of a static member from inside a dot-sourced ps1 file always works, setting a static member seems inconsistent.

test.ps1:

class A
{
    static $val
    A()
    {
        [A]::val = "empty"
    }
}

$A = [A]::new()

write-host $([A]::val)

[A]::val = "test"

. .\test2.ps1

write-host $([A]::val)

test2.ps1

[A]::val = "val"

Console output:

empty
test

Console output I expected:

empty
val

So, I added a write-host to test2.ps1:

[A]::val = "val"

write-host $([A]::val)

And ran it again:

empty
val
val

Okay, I say to myself.
I remove the write-host from test2.ps1 and I get another unexpected console output:

empty
val

Am I missing something ?

1

There are 1 best solutions below

0
SnoopTheDog On

As pointed by Santiago Squarzon, I just had to restart my code editor (VSCode) and the terminal I was executing the scripts in to start a new PSSession. Before I did that though, I found this way to circumvent the issue ;;

test.ps1

...
$x = ""

. .\test2.ps1

[A]::val = $x
...

test2.ps1

$x = "val"