Powershell variable life span (Function/Out of Function)

Experts,

I somewhat speak vbs, and understand most basics from that language.

In vbs, a variable dies at the end of a routine automatically, so if I were to have this code:

Sub subTest
     strVariable = "Some Value"
     'variable is alive here
End Sub

'variable is dead here

Open in new window


As soon as the Sub ended, "strVariable" would die.  If I wanted to counter this, I'd add "Dim strVariable" in the beginning of the script outside the Sub, so the PC would reserve memory for the variable I didn't want to die.

Dim strVariable

Sub subTest
     strVariable = "Some Value"
     'variable is alive here
End Sub

'variable is also alive here, do to memory reservation

Open in new window


How do I reproduce this in Powershell?  i.e., if by chance I wanted to store the variable called in a function indefinately, how would I go about doing that?  - Or does PS store the variable in memory for the life of the program anyway?

Ignore the fact that it's bad practice to keep variables alive outside of their scope.  This is just a conceptual question, added with the idea that what would happen if I created a hash table in PS within a function and needed to reference it later.
LVL 5
usslindstromAsked:
Who is Participating?
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
In PowerShell you try to use the pipeline to pass objects and results. So you would always use something like
  $strHashTable += get-hashtable $x $y $z
or
  get-hashtable $x $y $z | do-something
with the latter being better, as the result can be processed as soon as possible (while not built completely yet).

Though you can almost always translate VBS code very similar to PS code, you should not do that. PS is much more advanced in object access and processing.
0
 
footechCommented:
If you read the help for about_Scopes I think it will pretty much explain it all.  Here's a couple points:
- a variable created within a function does not exist outsite that function
- for a variable created outside a function, if you want to modify the variable inside the function, and have that change kept after the function ends, then you must specify the scope of the variable inside the function
0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
footech is absolutely correct. Different from VBS, variables are always local to the scope they are used in. Otherwise you would be able to "hack" functions and scripts by defining some vars (guessing their names), and then be able to get access to internal, very private stuff.

And you could never be sure about side effects only because you named the vars the same. Imagine a funciton modifiying your vars without you knowing it!

So for security and privacy, any other scope than $local needs to be explicitely noted. If you want to access script-local variables, $script:YourVarName here is what you use inside of functions (or everywhere, to make it clear the vars can get used and modified elsewhere).

Note that you can read variables from a "higher" scope, that is you have access to $script vars in functions of that script, but as soon as you change anything, a new (function-local) var is created.
0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
footechConnect With a Mentor Commented:
Here's a (not very sophisticated) example.  Save the code as a .PS1 file and then run it in a PS console.
function test
{
    "===="
    Write-Output "inside the function"
    $a 
    $a = $a + 2
    $a #this variable "a" is not the same as the "a" variable outside the function
    $script:a = "infinity"
    $a
    $a = $a + 2
    $a
    "===="
}

Write-Output "before the function"
$a = 2
$a
test
Write-Output "after the function"
$a
"===="

Open in new window

0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
What to expect:
before the function
2
====
2
4
6
====
after the function
infinity
====

Open in new window

Note that the function var $a is created with line 6, and any reference to $a in the function is to that modified copy.
0
 
usslindstromAuthor Commented:
Thank you both for your OUTSTANDING explinations.  I think I'm following.

Can you please bear with me while I wrap my head around what you're describing...  I get the basics.

Variables outside of their scope = bad.

Now, how would I convert this thought process?  In vbs, out of habbit, I would pass through a sub routine that would collect info from WMI and add results to a dictionary object.  Simple and clean.  Converting this idea to hash tables, you can see where the logic will be broken unless I keep the variable alive.

In this instance, I should put this inside the function:

$Script:$strHashTable.add("Key", "Value")

Open in new window

0
 
usslindstromAuthor Commented:
Thanks guys.  Much appreciated on the great writeups.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.