为什么 Powershell 不能正确处理带有美元符号和问号的字符串?

Why does Powershell not process a string correctly which has a dollar sign and a question mark?

在 PowerShell 中,为什么 return 什么都没有:

PS > $y = "$prid?api"
PS > echo $y

但这些效果更好:

PS > $y = "$prid\?api"
PS > echo $y
18\?api
PS > $y = "${prid}?api"
PS > echo $y
18?api

令人惊讶的是,? 可以用在 PowerShell 变量名 中,而不需要将名称包含在 {...}.

因此,根据 PowerShell 的 expandable strings 规则(在 "..." 字符串中进行字符串插值),"$prid?api" 查找具有逐字名称的变量 prid?api 而不是考虑? 隐式终止前面的标识符。

也就是说,您实际上可以定义和引用一个名为prid?api的变量,如下所示:

PS> $prid?api = 'hi'; $prid?api
hi

这种令人惊讶的宽容实际上阻碍了最近引入的语言功能,空条件访问,在 PowerShell(核心)7.1 中引入:

# v7.1+; note that the {...} around the name is - unexpectedly - *required*.
${variableThatMayBeNull}?.Foo()

GitHub issue #14025 提倡在这种情况下避免使用 {...}