What is the difference between dot (.) and ampersand (&) in PowerShell?
The difference between the
.
and&
operators matters only when calling PowerShell scripts or functions (or their aliases) - for cmdlets and external programs, they act the same.For scripts and functions,
.
and&
differ with respect to scoping of the definition of functions, aliases, and variables:&
, the call operator, executes scripts and functions in a child scope, which is the typical use case: functions and scripts are typically expected to execute without side effects:The variables, (nested) functions, aliases defined in the script / function invoked are local to the invocation and go out of scope when the script exits / function returns.
Note, however, that even a script run in a child scope can affect the caller's environment, such as by using
Set-Location
to change the current location, explicitly modifying the parent scope (Set-Variable -Scope 1 ...
) or the global scope ($global:...
) or defining process-level environment variables.
.
, the dot-sourcing operator, executes scripts and functions in the current scope and is typically used to modify the caller's scope by adding functions, aliases, and possibly variables for later use. For instance, this mechanism is used to load the$PROFILE
file that initializes an interactive session.
The caveat is that for functions (as opposed to scripts) the reference scope for child vs. current is not necessarily the caller's scope: if the function was defined in a module, the reference scope is that module's scope domain:
- In other words: trying to use
.
with a module-originated function is virtually pointless, because the scope getting modified is the module's. - That said, functions defined in modules aren't usually designed with dot-sourcing in mind anyway.
Like Mathias mentioned as a comment in this thread. &
is used to invoke the expression whatever comes after the &
and .
is used to invoke it in the current scope and is normally used to dot source a helper file which contains functions to make it available in callers scope.
- See https://mcpmag.com/articles/2017/02/02/exploring-dot-sourcing-in-powershell.aspx for more dot sourcing.