0

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
    Every test I tried so far produces "empty" followed by "val". I'm using PS 5.1, both in VSCode and stand alone. What version are you using and are you using VSCode? – Darin Mar 30 '23 at 15:27
  • same for me. im unable to replicate this on 7.4.0-preview.2 // did you try starting a fresh powershell session ? – Santiago Squarzon Mar 30 '23 at 15:28

1 Answers1

0

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"