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

问题描述

在 PowerShell 中,为什么这不返回任何内容

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 的变量而不是考虑 { {1}} 隐式终止前面的标识符。

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

prid?api

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

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

GitHub issue #14025 主张在这种情况下不需要使用 # v7.1+; note that the {...} around the name is - unexpectedly - *required*. ${variableThatMayBeNull}?.Foo()