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.

2 thoughts on “PowerShell: Using Shared Variables

  1. It was excited to come across your site a short while ago. I arrived here today hoping to learn interesting things. I was not upset. Your well thought out ideas with new strategies on this subject matter were enlightening and a great help to me. Thank you for making time to create these things and for sharing your mind.

  2. I like the valuable ioorfmatinn you provide in your articles. I will bookmark your blog and check again here frequently. I’m quite sure I will learn lots of new stuff right here! Best of luck for the next!

Leave a Reply

Your email address will not be published.