What is the difference between dot (.) and ampersand (&) in PowerShell?

后端 未结 4 928
天涯浪人
天涯浪人 2021-02-12 22:05

In PowerShell, what is the difference between using dot (.) and ampersand (&) when invoking a cmdlet, function, script file, or operable program?

4条回答
  •  忘了有多久
    2021-02-12 22:36

    • The difference between the . and & operators matters only when calling 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.

提交回复
热议问题