PowerShell 字符串插值语法 [英] PowerShell string interpolation syntax

查看:57
本文介绍了PowerShell 字符串插值语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是使用以下语法来确保变量在字符串中展开:

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 字符串插值语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆