1

I would like to understand the difference between invoking a PowerShell scriptblock with an ampersand (&) versus doing so using a dot (.).

For example, if I have a scriptblock like so:

$scriptBlock = { Write-Host -Object "Hello, $message" }

and we invoke it using an ampersand (&) operator like so:

$message = "World"
& $scriptBlock

the output is:

Hello, World

Invoking the same scriptblock with a dot (.) operator also gives the exact same output.

$message = "World"
. &scriptBlock

I would like to know if there are any differences in these two approaches.

albert
  • 8,285
  • 3
  • 19
  • 32
zsoumya
  • 133
  • 2
  • 10
  • 5
    `&` executes the command in a new scope, `.` executes the command in the callers scope. Change your scriptblock to `{$var = 123}` and then see if `$var` has a value after running with `&` vs with `.` – Mathias R. Jessen Apr 10 '17 at 19:36
  • Did you read _basic_ [About Operators](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_operators) article (or at least `Get-Help 'about_Operators' -ShowWindow`)? – JosefZ Apr 10 '17 at 19:39
  • 3
    @MathiasR.Jessen `.` not necessary use caller scope. If command bounded to different `SessionState`, then command always jump here: `$a=1; New-Module { $a=10; function f { ($a=$a+1) } } | Out-Null; f; f; f; . f; . f; . f; $a`. As you can see, caller scope `$a` are not affected by `. f`. – user4003407 Apr 11 '17 at 00:56

0 Answers0