【问题标题】:Retaining newlines in PowerShell string在 PowerShell 字符串中保留换行符
【发布时间】:2010-12-13 17:38:56
【问题描述】:

在 PowerShell 脚本中,我在变量中捕获 EXE 文件的字符串输出,然后将其与其他一些文本连接起来以构建电子邮件正文。

但是,当我这样做时,我发现输出中的换行符减少为空格,使总输出不可读。

# Works fine
.\other.exe

# Works fine
echo .\other.exe

# Works fine
$msg = other.exe
echo $msg

# Doesn't work -- newlines replaced with spaces
$msg = "Output of other.exe: " + (.\other.exe)

为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: string powershell newline


    【解决方案1】:

    或者您可以像这样简单地设置 $OFS:

    PS> $msg = 'a','b','c'
    PS> "hi $msg"
    hi a b c
    PS> $OFS = "`r`n"
    PS> "hi $msg"
    hi a
    b
    c
    

    来自man about_preference_variables

    输出字段分隔符。指定分隔 数组转换为字符串时的数组元素。

    【讨论】:

    • 赞成这一点,因为只有在您回答之后,我才意识到 $msg 没有被设置为单个字符串,而是默认连接的 行数组带空格。
    • 伟大的节省时间和隐藏的宝石。太棒了!
    • 很好的答案!谢谢!
    【解决方案2】:

    也许这有帮助:

    $msg = "Output of other.exe: " + "`r`n" + ( (.\other.exe) -join "`r`n")
    

    你从 other.exe 得到一个行列表而不是文本

    $a = ('abc', 'efg')
     "Output of other.exe: " + $a
    
    
     $a = ('abc', 'efg')
     "Output of other.exe: " +  "`r`n" + ($a -join "`r`n")
    

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 1970-01-01
      • 2021-08-28
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多