Solved

Powershell variable life span (Function/Out of Function)

Posted on 2014-04-29
7
767 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
  • 3
  • 2
  • 2
7 Comments
 
LVL 39

Expert Comment

by:footech
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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 39

Assisted Solution

by:footech
footech earned 250 total points
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
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 68

Accepted Solution

by:
Qlemo earned 250 total points
Comment Utility
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
Comment Utility
Thanks guys.  Much appreciated on the great writeups.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Citrix XenApp, Internet Explorer 11 set to Enterprise Mode and using central hosted sites.xml file.
Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
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)
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

743 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now