PowerShell Static Variables

It has been three years since I have been giving PowerShell sessions for a local user group in Chicago. In the last session, we discussed about PowerShell static variables. In this tutorial, I will explain how to work with static variables in PowerShell with examples.

Static variables in PowerShell are declared within a class using the static keyword and are shared across all instances of that class. For example, you can define a static variable $Counter in a class MyClass and increment its value using a static method IncrementCounter. This allows the variable to maintain a consistent state across multiple instances of the class, making it useful for scenarios where shared data or state management is required.

What are Static Variables in PowerShell?

Static variables in PowerShell are variables that belong to the class itself rather than to any specific instance of the class. This means that static variables are shared across all instances of the class. They are particularly useful when you need to maintain state or data that should be consistent across all instances.

Declare Static Variables in PowerShell

To declare a static variable in a PowerShell class, you use the static keyword. Here’s a simple example:

class MyClass {
    static [int]$Counter = 0

    static [void]IncrementCounter() {
        [MyClass]::Counter++
    }
}

# Accessing the static variable
[MyClass]::Counter  # Output: 0

# Incrementing the static variable
[MyClass]::IncrementCounter()
[MyClass]::Counter  # Output: 1

In this example, $Counter is a static variable that is shared among all instances of MyClass. The IncrementCounter method increments the value of $Counter.

The output is in the screenshot below. After I executed the above code using VS code,

PowerShell Static Variables

Read Set and Get Environment Variables in PowerShell

PowerShell Static Variables Example

Now, let me show you a practical example of how to use static variables in PowerShell.

Consider a scenario where you need to track the number of active user sessions in an application. Static variables can be handy in such cases.

class SessionManager {
    static [int]$ActiveSessions = 0

    [void]StartSession() {
        [SessionManager]::ActiveSessions++
        Write-Host "Session started. Active sessions: $([SessionManager]::ActiveSessions)"
    }

    [void]EndSession() {
        if ([SessionManager]::ActiveSessions -gt 0) {
            [SessionManager]::ActiveSessions--
            Write-Host "Session ended. Active sessions: $([SessionManager]::ActiveSessions)"
        } else {
            Write-Host "No active sessions to end."
        }
    }
}

# Creating instances
$session1 = [SessionManager]::new()
$session2 = [SessionManager]::new()

# Starting sessions
$session1.StartSession()  # Output: Session started. Active sessions: 1
$session2.StartSession()  # Output: Session started. Active sessions: 2

# Ending sessions
$session1.EndSession()    # Output: Session ended. Active sessions: 1
$session2.EndSession()    # Output: Session ended. Active sessions: 0

Here, ActiveSessions is a static variable that keeps track of the number of active sessions. The StartSession and EndSession methods modify this static variable.

Check out Generate Random Numbers in PowerShell

PowerShell Static Methods

In addition to static variables, PowerShell classes can also have static methods. Static methods are methods that can be called on the class itself rather than on an instance of the class. They are useful for operations that are related to the class as a whole.

Let me show you an example to help you understand it better.

class StringUtils {
    static [string]ToUpperCase([string]$input) {
        return $input.ToUpper()
    }

    static [string]ToLowerCase([string]$input) {
        return $input.ToLower()
    }
}

# Using static methods
[StringUtils]::ToUpperCase("hello world")  # Output: HELLO WORLD
[StringUtils]::ToLowerCase("HELLO WORLD")  # Output: hello world

In this example, StringUtils is a utility class with static methods for converting strings to upper and lower case. These methods can be called directly on the class without creating an instance.

I executed the above PowerShell script, and you can see the output in the screenshot below:

PowerShell Static Methods

PowerShell Static Methods Example

Let me give you another practical example of using static methods in PowerShell.

Static variables can also be used in configuration management scenarios where certain settings need to be consistent across the application.

class ConfigManager {
    static [string]$AppName = "MyPowerShellApp"
    static [string]$Version = "1.0.0"

    static [void]ShowConfig() {
        Write-Host "App Name: $([ConfigManager]::AppName)"
        Write-Host "Version: $([ConfigManager]::Version)"
    }
}

# Accessing configuration settings
[ConfigManager]::ShowConfig()
# Output:
# App Name: MyPowerShellApp
# Version: 1.0.0

In this case, AppName and Version are static variables that store the application’s name and version. The ShowConfig method displays these settings.

Conclusion

Static variables and methods in PowerShell are used to manage shared data and functionality within your scripts and applications. I hope you now understand how to use the static variables and methods in PowerShell. Also, I am sure these real examples will help you to learn more about the PowerShell static variables and methods.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.