【问题标题】:Why does Powershell not process a string correctly which has a dollar sign and a question mark?为什么 Powershell 不能正确处理带有美元符号和问号的字符串?
【发布时间】:2021-05-10 07:19:50
【问题描述】:

在 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

【问题讨论】:

  • 如果您有兴趣:我添加了有关 v7.1+ null-conditional 运算符(?.?[...])的信息,它们会发生冲突允许使用 ? 作为不带 {...} 的变量名的一部分。

标签: powershell special-characters dollar-sign


【解决方案1】:

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

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

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2012-03-13
    • 2015-08-21
    • 2011-11-16
    相关资源
    最近更新 更多