jkc
jkc

Reputation: 142

Variable scope in Powershell

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.

Upvotes: 0

Views: 292

Answers (1)

user459872
user459872

Reputation: 24582

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.

Upvotes: 4

Related Questions