【问题标题】:PowerShell "cat <file>" with blank lines treats blanks as spaces带有空行的 PowerShell“cat <file>”将空格视为空格
【发布时间】:2013-09-21 05:39:22
【问题描述】:

我看到很多帖子询问如何从 powershell 中的文件中删除空白行,但我试图保留它们,而不是在 send-mailmessage 调用中使用 bodyashtml。

我有一个文件,mail.txt,它是:

mail file blah blah blah

hshshshshs

当你 cat 那个文件时,它看起来没问题;主要问题是,当您将“cat”视为变量时,就像

$BLAH = $(cat ${MAIL_FILE})
echo "blah is $BLAH"

它返回

blah is mail file blah blah blah  hshshshshs

所以当它作为正文的一部分传递给发送邮件时:

$BODY = @"

this is line two

$(cat ${MAIL_FILE})
"@

send-mailmessage `
  -from ${FROM} `
  -to ${MAIL_RECIPIENT} `
  -subject ${SUBJECT} `
  -body ${BODY} `
  -smtpserver ${RELAYHOST} `
  -priority ${PRIORITY}

它在电子邮件中显示为

line two

mail file blah blah blah  hshshshshs

而不是

<blank line here>
line two

mail file blah blah blah

hshshshshshhs

那么我该如何“维护”文件原样,传递到邮件正文而不是作为附件?理想情况下,如何在该正文中获得前导空白行。

【问题讨论】:

    标签: powershell sendmail


    【解决方案1】:

    Get-Content(别名cat)实际上将内容读取为字符串数组,每个字符串代表一行。在 powershell 3.0 中,您可以使用 -Raw 标志来获取整个文件。

    $BLAH = cat ${MAIL_FILE} -Raw
    

    否则您可能会使用join 运算符:

    $BLAH = (cat ${MAIL_FILE}) -join "`r`n"
    

    【讨论】:

    • -join 成功了,谢谢!我应该提到我正在使用 2.0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2015-07-15
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多