Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Powershell variable life span (Function/Out of Function)

Posted on 2014-04-29
7
Medium Priority
?
846 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 41

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 71

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 41

Assisted Solution

by:footech
footech earned 1000 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
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
LVL 71

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 71

Accepted Solution

by:
Qlemo earned 1000 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

Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

688 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