View Single Post
Old 08-15-2008   #4 (permalink)
tojo2000


 
 

Re: Include another script, keep variables in included script?

On Aug 15, 8:18*pm, "Kiron" <Ki...@xxxxxx> wrote:
Quote:

> You can export the variables to tmp2's scope:
>
> -< tmp.ps1 >-
> param ([string[]]$exportVariable)
>
> $Test = "Here"
> $There = "There"
>
> echo "TEST: $test"
> echo "There: $there"
>
> if ($exportVariable) {
> *foreach ($var in $exportVariable) {
> * set-variable $var (get-variable $var).value -scope 1
> *}}
>
> -< tmp.ps1 >-
> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
> -< tmp2.ps1 >-
> # $test echo "TEST: $Test"
>
> # assuming both scripts are in same Dir
> $cmd = join-path (split-path $myInvocation.myCommand.path) tmp.ps1
> & $cmd -ex test, there
>
> echo "TEST: $Test"
> echo "There: $there"
> -< tmp2.ps1 >-
> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
> .\tmp2
>
> --
> Kiron
You might want to explain a solution like that, since variable
scoping, especially with the way PowerShell lets you do it, is a
difficult concept to get used to if you haven't dealt with it before.

When you assign a variable in PowerShell, by default the variable is
created in the current scope. If you are in a script block, then at
the end of the script block that variable will go "out of scope" and
be removed. Any script blocks or function calls after a variable is
declared, though, get access to the variable defined above.

The -scope option of Set-Variable allows you to set the scope of the
variable to a specific number of levels above the current scope. If
it is in a function, then it will set itself in the script's scope
that called it, and if it's in the script's highest scope then it will
be declared in the global scope.

The caveat with this method is that if you want to maintain that kind
of granularity then you have to know how many levels above the calling
statement you want the variable to be set to ahead of time. In
general it is a good idea to avoid declaring global variables as much
as possible because you increase your chances of having the same
variable name used twice, but this is not always practical.

BTW, if you do set the same variable twice then the innermost variable
will take precedence while it is in scope, and then you will revert to
the outer-scoped variable, since Powershell always starts with the
current scope and then works its way up when looking up a variable
name.
My System SpecsSystem Spec