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

后端 未结 4 923
天涯浪人
天涯浪人 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:39

    To segregate and give a clear understanding, I am explaining a scenario. Imagine you have function named MyFunction in a source.ps1. And you wish to use that function in another script(MyCustomScript.ps1)

    Put a line in MyCustomScript.ps1 like the below and you should be able to use it.

    . path\of\the\source.ps1 
    
    MyFunction
    

    So you are using the function which is present in source.ps1 in your custom script. Whereas, & is the call operator in Powershell which will help you to call any of the outside executable like psexec and others.

    Invoking a command (either directly or with the call operator) will create another scope known as child scope and will be gone once the command been executed. If the command is changing any of the values in a global variable then in that case the changes will be lost when the scope ends as well.

    To avoid this drawback and to keep any changes made to global variables you can dot the script which will always execute the script in your current scope.

    Dot sourcing will only run the function or script within the current scope and call operator (&) which will run a function or script as usual; but it will never add to the current scope.

    Hope this gives an idea on when to use what.

提交回复
热议问题