Beta 42

Research and Development


PowerShell - Using Shared Variables

By default, all variables created in functions are local, so they only exist within that function and all functions that are called from within this function.

Sometimes, you'd like to examine variables defined in a function after that function executed. Or you'd like to persist a variable, so next time the function is called it can increment some counter or continue to work with that variable rather than creating a brand new variable each time.

To achieve this, use shared variables by prepending Script: to a variable name. Here's a sample:

PS> function Call-Me { $script:counter ++; "You called me $script:counter times!" }
PS> Call-Me
You called me 1 times!
PS> Call-Me
You called me 2 times!
PS> Call-Me
You called me 3 times!

Note that the variable $counter now does not exist inside the function anymore. Instead, it is created in the context of the caller (the place where you called Call-Me). If you prepended a variable name with global:, the variable would be created in the topmost context and thus available everywhere.