Home > Enterprise >  powershell: How to create and access static variables in a powershell class?
powershell: How to create and access static variables in a powershell class?

Time:10-15

How to create a powershell class that has static variables?

class ex1 {
    static [int]$count = 0

    ex1() {
        [ex1]::count = [ex1]::count   1
        write-host [ex1]::count
    }
}

$ex1 = [ex1]::new()
$ex2 = [ex1]::new()
$ex3 = [ex1]::new()

exit 1

I tried this but all it does it prints:

[ex1]::new()
[ex1]::new()
[ex1]::new()

instead of incrementing the count to count the number of objects created in the static integer.

CodePudding user response:

Apart from the constructor ex1() {..}, you need to add a method that actually returns the value of the static property Count:

class ex1 {
    [int]static $count = 0

    ex1() {
        # constructor increments the static Count property
        [ex1]::count  
    }
    [int]GetCount() {
        # simply return the current value of Count
        return [ex1]::count
    }
}

$ex1 = [ex1]::new().GetCount()
$ex2 = [ex1]::new().GetCount()
$ex3 = [ex1]::new().GetCount()

$ex1, $ex2, $ex3   # --> resp. 1, 2, 3

CodePudding user response:

The static property works, but surprisingly the PowerShell parser does not leave argument mode when encountering [ex1]::count as a function argument, it is parsed as a literal string.

Enclosing [ex1]::count in parentheses fixes the problem by forcing the parser to leave argument mode and parse an expression.

class ex1 {
    static [int]$count = 0

    ex1() {
        [ex1]::count = [ex1]::count   1
        write-host ([ex1]::count)
    }
}

$ex1 = [ex1]::new()
$ex2 = [ex1]::new()
$ex3 = [ex1]::new()

[ex1]::count  # Works without parentheses, as we are not in argument mode.
  • Related