Solved

Powershell variable life span (Function/Out of Function)

Posted on 2014-04-29
7
826 Views
Last Modified: 2014-05-07
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.
0
Comment
Question by:usslindstrom
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 40

Expert Comment

by:footech
ID: 40030055
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
 
LVL 70

Expert Comment

by:Qlemo
ID: 40030140
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
 
LVL 40

Assisted Solution

by:footech
footech earned 250 total points
ID: 40030172
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
Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

 
LVL 70

Expert Comment

by:Qlemo
ID: 40030191
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
 
LVL 5

Author Comment

by:usslindstrom
ID: 40030600
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
 
LVL 70

Accepted Solution

by:
Qlemo earned 250 total points
ID: 40030856
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
 
LVL 5

Author Closing Comment

by:usslindstrom
ID: 40049407
Thanks guys.  Much appreciated on the great writeups.
0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question