powershell - PowerShell 字符串插值语法
问题描述
我总是使用以下语法来确保变量在字符串中展开:
"my string with a $($variable)"
我最近遇到了以下语法:
"my string with a ${variable}"
它们是等价的吗?有什么区别吗?
解决方案
为了补充marsze 的有用答案:
${...}
如果变量名包含特殊字符{
,例如空格、、或}
.
-
- 不特别的是
_
和 -令人惊讶和有问题的-?
。 - 注意:
:
总是被解释为终止 PowerShell驱动器引用,在命名空间变量表示法的上下文中,无论是否{...}
使用或需要外壳(例如,在$env:USERNAME
或中${env:USERNAME}
,env
指代表示所有环境变量的PowerShell 驱动器)。
在字符串扩展(插值) inside的上下文中"..."
,还有另一个使用${...}
的理由,即使变量名本身不需要它:
如果您需要直接从非空白字符后面描述变量名称,特别是包括:
:
$foo = 'bar' # example variable
# INCORRECT: PowerShell assumes that the variable name is 'foobarian', not 'foo'
PS> "A $foobarian."
A . # Variable $foobarian doesn't exist -> reference expanded to empty string.
# CORRECT: Use {...} to delineate the variable name:
PS> "A ${foo}barian."
A barbarian.
# INCORRECT: PowerShell assumes that 'foo:' is a *namespace* (drive) reference
# (such as 'env:' in $env:PATH) and FAILS:
PS> "$foo: bar"
Variable reference is not valid. ':' was not followed by a valid variable name character.
Consider using ${} to delimit the name.
# CORRECT: Use {...} to delineate the variable name:
PS> "${foo}: bar"
bar: bar
有关 PowerShell 字符串扩展规则的全面概述,请参阅此答案。
请注意,在将不带引号的参数传递给命令的上下文中,隐式应用字符串扩展时,您需要相同的技术;例如:
# INCORRECT: The argument is treated as if it were enclosed in "...",
# so the same rules apply.
Write-Output $foo:/bar
# CORRECT
Write-Output ${foo}:/bar
最后,一个有点晦涩的替代方法是`
-escape 变量名后面的第一个字符,但问题是这仅适用于不属于转义序列的字符(请参阅参考资料about_Special_Characters
):
# OK: because `: is not an escape sequence.
PS> "$foo`: bar"
bar: bar
# NOT OK, because `b is the escape sequence for a backspace character.
PS> "$foo`bar"
baar # The `b "ate" the trailing 'r' of the variable value
# and only "ar" was the literal part.
推荐阅读
- python - python pulsar concumer 收到消息时被阻塞
- reactjs - 如何在 React 和 NextJS 中管理依赖项?
- vue.js - 在单个 Vue 导航中重定向两次
- spring-webflux - Reactive Spring 中的生命周期回调(PostConstruct、PreDestroy)
- java - register() 和 @ComponentScan 的区别
- node.js - Node.js Oracle 数据库连接错误:错误:TypeError:oracle.getconnection 不是函数
- scala - 将数组结构拆分为单值列 Spark scala
- python - 张量流中RMSPROP优化器的初始化
- json - Hive 将 JSON 数组中的每个 JSON 元素分解为行
- python - 为什么烧瓶重定向给我一个空白页?