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

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

    You can also run things inside a module scope with the call operator, from my notes from Windows Powershell in Action.

    # get and variable in module scope
    $m = get-module counter
    & $m Get-Variable count
    & $m Set-Variable count 33
    
    # see func def
    & $m Get-Item function:Get-Count
    
    # redefine func in memory
    & $m {
      function script:Get-Count
      {
        return $script:count += $increment * 2
      }
    }
    
    # get original func def on disk
    Import-Module .\counter.psm1 -Force
    

    A few other things:

    # run with commandinfo object
    $d = get-command get-date
    & $d
    
    # call anonymous function
    & {param($x,$y) $x+$y} 2 5
    
    # same with dot operator
    . {param($x,$y) $x+$y} 2 5
    

提交回复
热议问题