PowerShell Call Operator (&)

Image Description

Daily PowerShell #39

Daily PowerShell Basics

November 24, 2021

quote Discuss this Article

In this blog post, we’ll learn how to use the call operator.

What is the PowerShell Call Operator?

The PowerShell call operator is used for invoking expressions that include variables, strings or script blocks as executable code. For example, you may assign an executable path to a variable and invoke it using the call operator.

$Notepad = "notepad.exe"
& $notepad

The call operator does not bring artifacts like variables, aliases or functions into the current scope when invoking PowerShell scripts. This is different than when dot sourcing scripts.

& .\myScript.ps1

Using Variables with the Call Operator

You can use variables both as the executable or as parameters to the executable when using the call operator.

$Notepad = "notepad.exe"
& $notepad

$File = "powershell.ps1"
& code $File

Invoking Script Blocks with the Call Operator

The call operator can also be used to call script blocks. It will not bring any artifacts generated by that script block into the current scope.

& { $Variable = 123 }

Invoking Scripts with the Call Operator

Te call operator can also be used to call scripts. Unlike dot-sourcing, it will not bring anything into the current scope.

'$Variable = 123' | Out-File .\script.ps1
& .\script.ps1