我总是使用以下语法来确保变量在字符串中展开:
I always used the following syntax to be sure that variable were expanded in a string:
"我的字符串带有 $($variable)"
我最近遇到了以下语法:
I recently ran into the following syntax:
我的带有 ${variable} 的字符串"
它们是等价的吗?有什么不同吗?
Are they equivalent? Any difference?
推荐答案补充 marsze 的有用回答:
${...}(将变量名括在 { 和 } 中)确实 always如果变量名称包含特殊字符(例如空格或 .),则必须使用
${...} (enclosing the variable name in { and }) is indeed always necessary if a variable name contains special characters (such as spaces or .)
在"..."中字符串扩展(插值)的上下文中,还有另一个使用 ${...} 的原因,即使变量名本身不需要它:
In the context of string expansion (interpolation) inside "...", there is another reason to use ${...}, even if the variable name itself doesn't need it:
如果您需要从紧跟在非空白字符之后的变量名中划分,特别是包括::
If you need to delineate the variable name from directly following non-whitespace characters, notably including ::
$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 字符串扩展规则的全面概述,请参阅此答案.
See this answer for a comprehensive overview of PowerShell string-expansion rules.
请注意,在将未加引号的参数传递给命令的上下文中,隐式应用字符串扩展时,您需要使用相同的技术;例如:
Note that you need the same technique when string expansion is implicitly applied, in the context of passing an unquoted argument to a command; e.g.:
# 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最后,一个有点晦涩的替代方法是 ` - 转义变量名后的第一个字符,但问题是这仅适用于不属于 的字符转义序列(参见about_Special_Characters):
Finally, a somewhat obscure alternative is to `-escape the first character after the variable name, but the problem is that this only works as expected with characters that aren't part of escape sequences (see 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 seemingly "ate" the trailing 'r' of the variable value.更多推荐
PowerShell 字符串插值语法
发布评论