I want to run or include a PS script from within another PS script. But
want the values set in the 2nd one to be available in the first one.
tmp.ps1----
$Test = "Here"
$There = "There"
echo "TEST: $test"
echo "There: $there"
------------------------
Now tmp2.ps1-------------
echo "TEST: " $Test
.\tmp.ps1
echo "TEST: " $Test
echo "There: " $there
-------------
.\tmp2.ps1
TEST: Here
There: There
--------------------------
I'd like the values set in 'tmp' to be available in tmp2. How do I do this?
Thx,
In addition to Kryten's answer, you can use the dotsource operator to
essentially run the script in the same scope.
You can think of the dotsource operator as injecting the script into
the current scope as if it were pasted in at that location. Normally
when you run a script, any variables and functions created inside the
script are created in the script's scope, and disappear with the
script as soon as it is done running. The dotsource operator runs the
script in the current scope.
The dotsource operator is a dot '.'.
To use it you put a dot and a space before the script. In this
example my script has a single variable, $scriptvar, that is set to
true inside scriptvar.ps1:
C:\Users\timjohnson\Documents> .\scriptvar.ps1
C:\Users\timjohnson\Documents> $scriptvar
C:\Users\timjohnson\Documents> . .\scriptvar.ps1
C:\Users\timjohnson\Documents> $scriptvar
True
One caveat: since it will run the script in the current scope you
can't run the script inside a script block or the imported variables
will disappear when the scriptblock is exited. In that case you'll
have to declare your variables as global.
Here's a script I came up with for importing scripts that I use, where
I try to solve the problem of having hardcoded script names, but
because I call the dotsource operator from inside the function I have
to declare all of my functions and variables that I want to import in
the global scope: http://tasteofpowershell.blogspot.com/2008/07/importing-scripts-as-libraries-part.html
I'd be interested to hear what other people have done.
Notet: If you're using PowerShell v2 CTP2 rather than v1 then you
should read up on creating modules, which is a new feature that
resolves most of these issues.