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

twa*_*lig 1 powershell special-characters dollar-sign

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

PS > $y = "$prid?api"
PS > echo $y
Run Code Online (Sandbox Code Playgroud)

但这些效果更好:

PS > $y = "$prid\?api"
PS > echo $y
18\?api
PS > $y = "${prid}?api"
PS > echo $y
18?api
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 5

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

因此,基于 PowerShell 的可扩展字符串规则(字符串内的字符串插值"..."),"$prid?api"查找具有逐字名称的变量,prid?api而不是考虑?隐式终止前面的标识符。

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

PS> $prid?api = 'hi'; $prid?api
hi
Run Code Online (Sandbox Code Playgroud)

这种令人惊讶的宽容实际上妨碍了PowerShell (Core) 7.1 中引入的最近引入的语言功能null-conditional access

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

GitHub 问题 #14025主张避免{...}在这种情况下使用。