vik santata
vik santata

Reputation: 3109

For powershell executing another powershell, what's the difference between "&" and "."

Like:

& another.ps1

And

. another.ps1

What's their difference? I wish to take the output text of another powershell script, while not wanting to import the internal functions defined in the other script. What statement can I use? I found even "&" command will automatically import all function definitions of the other powershell script.

Thank you.

Upvotes: 1

Views: 95

Answers (1)

mjolinor
mjolinor

Reputation: 68273

The difference is scope. & will run the script in it's own scope. . will run the script in the current scope.

$ErrorView = 'CategoryView'
$x = 'Test'

. { Get-variable x -Scope 0 }
& { Get-Variable x -Scope 0 }


Name                           Value                                                                      
----                           -----                                                                      
x                              Test                                                                       
ObjectNotFound: (x:String) [Get-Variable], ItemNotFoundException

In first example, the script is dot-sourced into the current scope, and $x is visible at Scope 0.

In the second example, the script is invoked with the & operator and $x is not visible at Scope 0.

Upvotes: 6

Related Questions