在PowerShell中,在调用cmdlet、函数、脚本文件或可操作程序时,使用点(.)和符号(&)有什么区别?
例如:
. foo.sh1
& foo.sh1有一个非常类似的问题被错误地关闭为一个重复:Differences between ampersand (&) and dot (.) while invoking a PowerShell scriptblock。问题是不同的,有完全不同的关键字和搜索排名。 shorthand for in a PowerShell pipeline?上的答案只回答了一半的问题。
发布于 2019-02-13 22:34:07
E 217E 118脚本E 219E 120或E 221E 122函数E 223(或它们的别名)-对于cmdlet和外部程序, & 和运算符之间的差异仅与有关。对于脚本和函数,. 和 & 在 functions, aliases,和E 249E 150变量E 251的定义的范围方面有所不同。- [**`&`****, the** _**call operator**_](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#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**_](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#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.注意,对于函数(而不是脚本),子函数和当前函数的引用范围不一定是调用者的作用域:如果函数是在模块中定义的,那么引用范围就是模块的作用域。
换句话说:尝试将.与模块起源的函数一起使用实际上是毫无意义的,因为修改的范围是模块的。也就是说,在模块中定义的函数通常都不是在考虑点源的情况下设计的。发布于 2019-02-13 03:23:13
就像Mathias在this线程中提到的注释一样。&用于调用表达式,无论在&和.之后调用它在当前作用域中如何,并且通常用于点源一个助手文件,该文件包含使其在调用者作用域中可用的函数。
发布于 2020-06-14 22:49:01
您还可以使用call运算符在模块范围内运行一些东西,这可以从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还有几件事:
# 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 5https://stackoverflow.com/questions/54661916
复制相似问题