【问题标题】:New line for all strings added to one添加到一个的所有字符串的新行
【发布时间】:2016-01-13 21:02:23
【问题描述】:

如何将所有字符串添加到一个变量中,每个变量都在新行中 我已经尝试了所有这些选项,但似乎没有任何效果 *这里所有的变量类型都是字符串,所以这不是问题

$Body = $alerts[1].description("'n") + $alerts[1].name("'n") + alerts[1].timeadded

$Body = $alerts[1].description "`n" + $alerts[1].name "`n" + $alerts[1].timeadded

$Body = $alerts[1].description `n + $alerts[1].name `n + $alerts[1].timeadded

$Body = $alerts[1].description `n  $alerts[1].name `n $alerts[1].timeadded

我希望$body 的输出每个都出现在新行中:

$alerts[1].description
$alerts[1].name
$alerts[1].timeadded

【问题讨论】:

    标签: powershell formatting output newline carriage-return


    【解决方案1】:

    我相信您正在寻找的是:

    $Body = $alerts[1].description + "`n" + $alerts[1].name + "`n" + $alerts[1].timeadded
    

    字符 `n 对应一个换行符,它应该按照您的描述连接字符串。

    【讨论】:

    • 这似乎不能让它变得简单尝试运行这个: $a = "AAA" $b = "BBB" $c = "CCC" $newline = $a + "\n" + $b + "\n" $c
    • @Fenomatik 检查已更正的更新答案。
    【解决方案2】:

    在制作格式很重要的多行字符串时,您始终可以使用here string 和/或format operator

    $Body = @"
    $($alerts[1].description)
    $($alerts[1].name)
    $($alerts[1].timeadded)
    "@
    

    或者

    $Body = @"
    {0}
    {1}
    {2}
    "@ -f $alerts[1].description, $alerts[1].name, $alerts[1].timeadded
    

    或者

    $Body = "{0}`r`n{1}`r`n{2}" -f $alerts[1].description, $alerts[1].name, $alerts[1].timeadded
    

    当您开始添加更多信息时,这两种方法的特点会更加明显。

    $Body = @"
    The alert is described as: {0}
    It has a name of {1}
    This happened at {2} local time.
    "@ -f $alerts[1].description, $alerts[1].name, $alerts[1].timeadded
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2023-04-06
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      相关资源
      最近更新 更多