Constant variables
Declare a immutable variable
.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
-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
- the variable is stored in the script’s global scope but cannot be accessed there
Mutate a static variable
Sources:
- 2023-03-21: Set-Variable (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
- 2023-03-21: Does PowerShell support constants? - Stack Overflow
- 2023-03-21 PowerShell Variable Scope Guide: Using Scope in Scripts and Modules
- 2023-03-21: about Scopes - PowerShell | Microsoft Learn
Tags:
Programm PowerShell - Learn PowerShell’s programming paradigms