PowerShell 字符串插值语法

编程入门 行业动态 更新时间:2024-10-23 07:21:15
本文介绍了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 字符串插值语法

本文发布于:2023-11-08 14:07:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   语法   插值   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!