PowerShell 格式化字符串

发布于 2025-01-16 19:02:58 字数 386 浏览 1 评论 0原文

我有一个字符串,我想动态插入一个变量。例子;

$tag = '{"number" = "5", "application" = "test","color" = "blue", "class" = "Java"}'

我想要完成:

$mynumber= 2
$tag = '{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}'

我想要将变量插入到字符串中,但是它没有执行。我猜 '' 将所有设置为字符串。关于我应该如何处理这个问题有什么建议吗?

PowerShell 测试和反复试验。还有谷歌。

I have a string that I want to insert dynamically a variable. Example;

$tag = '{"number" = "5", "application" = "test","color" = "blue", "class" = "Java"}'

I want to accomplish:

$mynumber= 2
$tag = '{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}'

I want to have the variable inserted on the string, but it is not going through. I guess the '' sets all as a string. Any recommendations on how should I approach this?

PowerShell test and trial and error. Also Google.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一身软味 2025-01-23 19:02:58

要添加到 Mathias 的有用答案

  • 错误地期望在 '...' 内进行字符串插值 字符串(与 "..." 内部相对)之前已经出现过很多次,像您这样的问题通常会作为 这篇文章


  • 但是,您的问题值得单独回答,因为:

    • 您的用例引入了一个后续问题,即嵌入 " 字符不能在 "..." 内按原样使用.

    • 更一般地说,链接的帖子处于参数传递的上下文中,其中适用其他规则。


注意:下面的一些链接指向概念性 about_Quoting_Rules 帮助主题。

在 PowerShell 中:

  • "..." 字符串(双引号,称为 可扩展字符串执行字符串插值,即变量值的扩展(例如 "... $var" 和子表达式(例如 "... $($var.Prop)"


  • 不是 '...' 字符串(单引号,称为 逐字字符串),其值按逐字(字面意思)使用。

对于 "..."如果字符串值本身包含 " 字符。

相关答案:


字符串插值的替代方案

在某些情况下,动态构造字符串的其他方法也可能有用:

  • 使用(逐字)模板字符串占位符,带有-f格式运算符

    $mynumber= 2
    # {0} 是第一个 RHS 操作数的占位符({1} 是第二个操作数,...)
    '“number”=“{0}”,...' -f $mynumber # -> “数字”=“2”,...
    
  • 使用简单的字符串连接 /em> 与+ 运算符:

    $mynumber= 2
    '"number" = "' + $mynumber + '", ...' # -> “数字”=“2”,...
    

To add to Mathias' helpful answer:

  • Mistakenly expecting string interpolation inside '...' strings (as opposed to inside "...") has come up many times before, and questions such as yours are often closed as a duplicate of this post.

  • However, your question is worth answering separately, because:

    • Your use case introduces a follow-up problem, namely that embedded " characters cannot be used as-is inside "...".

    • More generally, the linked post is in the context of argument-passing, where additional rules apply.


Note: Some links below are to the relevant sections of the conceptual about_Quoting_Rules help topic.

In PowerShell:

  • only "..." strings (double-quoted, called expandable strings) perform string interpolation, i.e. expansion of variable values (e.g. "... $var" and subexpressions (e.g., "... $($var.Prop)")

  • not '...' strings (single-quoted, called verbatim strings), whose values are used verbatim (literally).

With "...", if the string value itself contains " chars.:

  • either escape them as `" or ""

    • E.g., with `"; note that while use of $(...), the subexpression operator never hurts (e.g. $($mynumber)), it isn't necessary with stand-alone variable references such as $mynumber:

      $mynumber= 2
      $tag = "{`"number`" = `"$mynumber`", `"application`" = `"test`",`"color`" = `"blue`", `"class`" = `"Java`"}"
      
    • Similarly, if you want to selectively suppress string interpolation, escape $ as `$

      # Note the ` before the first $mynumber.
      # -> '$mynumber = 2'
      $mynumber = 2; "`$mynumber` = $mynumber"
      
    • See the conceptual about_Special_Characters help topic for info on escaping and escape sequences.

    • If you need to embed ' inside '...', use '', or use a (single-quoted) here-string (see next).

  • or use a double-quoted here-string instead (@"<newline>...<newline>"@):

    • See Mathias' answer, but generally note the strict, multiline syntax of here-strings:
      • Nothing (except whitespace) must follow the opening delimiter on the same line (@" / @')
      • The closing delimiter ("@ / '@) must be at the very start of the line - not even whitespace may come before it.

Related answers:


Alternatives to string interpolation:

Situationally, other approaches to constructing a string dynamically can be useful:

  • Use a (verbatim) template string with placeholders, with -f, the format operator:

    $mynumber= 2
    # {0} is the placeholder for the first RHS operand ({1} for the 2nd, ...)
    '"number" = "{0}", ...' -f $mynumber # -> "number" = "2", ...
    
  • Use simple string concatenation with the + operator:

    $mynumber= 2
    '"number" = "' + $mynumber + '", ...' # -> "number" = "2", ...
    
岁吢 2025-01-23 19:02:58

您当前的尝试不起作用的原因是 PowerShell 中的单引号 (') 字符串文字是逐字字符串 - 不会尝试扩展子表达式管道或变量表达式。

如果您想要一个可扩展的字符串文字,而不必转义字符串本身中包含的所有双引号 ("),请使用此处字符串:

$mynumber = 2

$tag = @"
{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}
"@

The reason your current attempt doesn't work is that single-quoted (') string literals in PowerShell are verbatim strings - no attempt will be made at expanding subexpression pipelines or variable expressions.

If you want an expandable string literal without having to escape all the double-quotes (") contained in the string itself, use a here-string:

$mynumber = 2

$tag = @"
{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}
"@
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文