65

I have several scripts that could be reusing variables so I'd like to isolate variables in their own Variables.ps1 script, i.e.

$var1 = "1"
$var2 = "2"

I'm trying to load these variables then print them out in the Main.ps1 script like this:

.\Variables.ps1
$var1
$var2

This works if I first run .\Variables.ps1 but not if I just run Main.ps1. My environment is PowerShell ISE. What am I doing wrong?

3 Answers 3

115

The variables declared in Variables.ps1 are at "Script Scope". That is you can not see them outside of the scope of the script that declares them. One way to bring the variables in Variables.ps1 to the scope of main.ps1 is to "dot source" Variables.ps1. This, in effect, runs Variables.ps1 at the scope of main.ps1. To do this, just stick a period and space before your invocation of the script:

. .\Variables.ps1
$var1
$var2
Sign up to request clarification or add additional context in comments.

2 Comments

totally agree with that solution, in my case i encountered small issue with the path to file, even though all files were in same dir, i had to add absolute path to file as different users had to be able to execute it so it is something like this: . ./absolute/path/to/file/Variables.ps1
@T.J. that is why I always use $PSScriptRoot to create an absolute path like this: $PSScriptRoot\Variables.ps1
44
# var.ps1
$Global:var1 = "1"
$Global:var2 = "2"

This works. Whether it's better or worse than "dot sourcing" probably depends on your specific requirements.

PS > .\var.ps1
PS > $var1
1
PS > $var2
2
PS >

Comments

-1

Just to ensure correctness ... try this... in main.ps1

echo "Test"
. .\Variables.ps1
echo $var1
echo $var2

2 Comments

I'm seeing just the "Test" output.
Exactly what user "zdan" mentions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.