Using persisting variables inside functions

by Jul 6, 2018

By default, when a PowerShell function exits, it “forgets” all internal variables. However, there is a workaround that creates persisting internal variables. Here is how:

# create a script block with internal variables
# that will persist
$c = & { 
    # define an internal variable that will 
    # PERSIST and keep its value even though
    # the function exits
    $a = 0

    {
        # use the internal variable
        $script:a++
        "You called me $a times!"
    }.GetNewClosure()
}

This code creates a script block with an internal variable that keeps its value. When you run this script block multiple times, the counter increments:

 
PS> & $c 
You called me 1 times!

PS> & $c 
You called me 2 times!

PS> & $c 
You called me 3 times!   
 

Yet, the variable $a inside the script block is neither global nor scriptglobal. It only exists inside the script block:

 
PS> $a 
 

To turn the script block into a function, add this:

 
PS> Set-Item -Path function:Test-Function -Value $c 

PS> Test-Function
You called me 5 times!

PS> Test-Function
You called me 6 times!
 

Twitter This Tip! ReTweet this Tip!