0

I am new to Powershell and I have noticed something that I can't quite understand.

Given two scripts:

#Script 1
$test = "This is a test"
& ".\script2.ps1"
#Script 2
Write-Host $test

When I run script1 "This is a test" is printed.

My question is: why can script2 see the variable defined in script1 when the variable isn't defined as global?

The only reason I can think of is that script2 isn't called but just imported by '&' but I'm not sure this is corret.

2
  • 3
    Please read about_Scopes Commented Sep 26, 2022 at 12:06
  • 1
    PowerShell uses dynamic scoping (instead of lexical scoping, as most other languages like C# do). A child scope copies the variables of the parent scope, so it can read their values but can't modify them directly (for reference type variables, it can modify properties though). Commented Sep 26, 2022 at 12:54

1 Answer 1

4

Here & is the Call operator.

The call operator executes in a child scope and the calling scope is the parent scope. Quoting from the documentation,

The functions or scripts you call may call other functions, creating a hierarchy of child scopes whose root scope is the global scope. Unless you explicitly make the items private, the items in the parent scope are available to the child scope.

Sign up to request clarification or add additional context in comments.

Comments

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.