js2010 的有用答案 https://stackoverflow.com/a/57677699/45375显示正确的解决方案:
因为你的命令名称/路径包含变量引用 ($PROGPATH/...
),您必须使用它来调用它&
: & $PROGPATH\program args...
如果分组表达,(...) https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#grouping-operator--被使用,或者子表达式,$(...) https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#subexpression-operator--参与。
Additionally, the same applies if a command name/path is quoted ('...'
or "..."
)[1], as is required if the path contains spaces, for instance.
To put it differently: Direct invocation is only supported if the command name/path is a verbatim, unquoted string[1]; in all other cases, &
must be used.
As for why:
有必要强制将一个声明解释为command,即将其解析为论证模式(见下文),从而导致命令执行而不是表达评估.
PowerShell 有两个基本功能解析模式 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing:
-
论证模式, which 工作原理就像传统外壳,其中第一个标记是命令名/路径,例如 cmdlet 或外部程序,后续标记代表参数,仅当它们包含 shell 时才需要引用元字符(字符。对于 PowerShell 具有特殊含义,例如用于分隔标记的空格)。
-
表达方式, which 就像表达式一样工作编程语言.
PowerShell 根据语句做出决定第一个令牌应用什么解析模式:
如果除其他外,第一个标记以变量引用或者是一个带引号的字符串, PowerShell 解析中表达方式.
- 在表达模式下,
\
开始一个新的令牌,以及无法识别的令牌\program
结果出现您看到的语法错误。
- (如果您使用过
/
,它会被解释为除法运算符, and program
不是有效的除数操作数。)
[1] Note that if your executable path is a literal string (doesn't contain variable references of expressions) you may alternatively `
-escape individual characters (spaces) in lieu of enclosing entire string in '...'
or "..."
, in which case &
is then not necessary; e.g.:
C:\Program` Files\Notepad++\notepad++.exe
With a literal string you can even employ partial single- or double-quoting as long as the first token is unquoted; e.g.:
C:\"Program Files"\Notepad++\notepad++.exe