无法使用变量在powershell中发送电子邮件

时间:2014-05-07 05:09:27

标签: email powershell send

我在powershell中使用下面的脚本来发送电子邮件警报。我收到了电子邮件,但我没有收到临时变量的确切正文消息。

$file= get-content sample.txt
Send-MailMessage -SmtpServer serverip -f mymailid@domain.com -to mymailid@domain.com -Subject 'Test Msg' -Body "$file"

1 个答案:

答案 0 :(得分:0)

如果您有PowerShell V3,请尝试这种方式:

$file = Get-Content sample.txt -raw
Send-MailMessage ... -Body $file

在早期版本中试试这个:

$file = Get-Content sample.txt
$OFS = "`n"
Send-MailMessage ... -Body "$file"
$OFS = $null
如果文件中有多行,并且您没有使用Get-Content的-Raw参数,那么

$ file将是一个字符串数组。在这种情况下,将该变量放在双引号内会导致PowerShell使用$ OFS的内容作为每个元素的分隔符来连接数组的每个元素。如果未设置$ OFS,则PowerShell使用空格。但是,您希望换行符保留原始文件上的结构。无论如何,如果你有V3,只需使用-Raw,所有这些$ OFS的东西都没关系。