powershell格式为字符串

发布于 2025-01-25 00:37:11 字数 385 浏览 4 评论 0 原文

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

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

我想完成:

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

我想在字符串上插入变量,,但它没有通过。我猜“”将全部设置为字符串。关于我该如何处理的任何建议?

Powershell测试以及反复试验。还有Google。

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-02-01 00:37:11

要添加到 Mathias'有用的答案

  • 错误地期望在'...'...'...'...'字符串(而不是内部“ ...” )以前出现了很多次,诸如您的问题通常会以此帖子


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

    • 您的用例引入了后续问题,即嵌入式 字符在“ ...”中无法用作字符。

    • 更一般地,链接的帖子是在 crign-passing 的上下文中,其中其他规则适用。


注意:下面的一些链接与概念 about_quoting_rules 帮助主题。

在PowerShell中:

  • 唯一“ ...” strings (双引号,称为 可扩展字符串 强>,即变量值的扩展(例如“ ... $ var” 和subexpressions(例如,“ ... $($ var.prop)” )< /p>

  • '...' strings(单引号,称为 verbatim strings ),其值使用 verbatim (实际上是)。<<<<<<<<<<<<<<<<<<<<<<<<<< /p>

使用“ ...” 如果字符串值本身包含chars。

相关答案:


替代方案字符串插值:

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

  • 使用(verbatim) template string 占位符,带有 -f 格式运算符

      $ mynumber = 2
    #{0}是第一个RHS Operand({1}的占位符),第二,...)
    '“ number” =“ {0}”,...'-f $ mynumber# - &gt; “数字” =“ 2”,...
     
  • /em>使用+操作员:

      $ mynumber = 2
    '“ number” =“' + $ mynumber +'”,...'# - &gt; “数字” =“ 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-02-01 00:37:11

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

如果您想要一个可扩展的字符串文字而无需逃脱字符串本身中包含的所有双引号(),请使用此处的字符串:

$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 和您的相关数据。
原文