Constant variables

Declare a immutable variable

New-Variable TEST -Option ReadOnly -Force -Value 100
  • .Option ReadOnly: Cannot be changed, except by using the Force parameter.
  • -Force: Override previous definitions including debugging
  • Can be deleted using Remove-Variable TEST -Force

Declare a baked variable

New-Variable TEST -Option Constant -Force -Value 100
  • -Option Constant: The variable can neither be edited nor removed forever
  • -Force: Override previous definitions including debugging
  • complicates debugging

Static function variables

Static variables have a lifetime that lasts until the end of the program, instead of loosing their value when execution leaves their scope. This is useful for sharing information like a counter when repeatedly calling a function.

PowerShell doesn’t natively provide a way1 to create static variables, but we can store the variable globally and restrict access to only the function that declared it. Since the function is stored globally, the name cannot be used elsewhere.

Variables created within functions or scripts do not effect the parent scope, unless you explicitly specify the scope2 using Scope Modifiers or a Scope parameter.

Declare and initialize a static variable

function Get-StaticVariable {
    if (-not (Test-Path variable:staticVariable)) {
        New-Variable -Name staticVariable -Value $initialValue -Scope Script -Visibility Private
    }
    return $script:staticVariable
}
  • the variable is stored in the script’s global scope but cannot be accessed there

Mutate a static variable

function Get-IncrementedStaticCounter {
    if (-not (Test-Path variable:staticCounter)) {
        New-Variable -Name staticCounter -Value $initialValue -Scope Script -Visibility Private
    }
    $script:staticCounter++
    return $script:staticCounter
}

Sources:

Related:
Data Types - Ensure correct content and members with strongly type variables like booleans, hashtables, or dictionaries

Tags:
Programm PowerShell - Learn PowerShell’s programming paradigms

Footnotes

  1. 2023-03-21: Static variables - Variables - PowerShell | Microsoft Learn

  2. 2023-03-21: Parent and Child Scopes - about Scopes - PowerShell | Microsoft Learn