Powershell:在Email中添加新行

时间:2019-01-15 09:26:33

标签: powershell powershell-v2.0 powershell-v3.0

我需要检查磁盘并发送一封状态为电子邮件的邮件。

但是我得到的只是一个行内的实体,而不是'r'n。怎么了?

$smtpserver = "server"
$from = "from"
$to = "to"
$subject = "subject"

$servernames = Get-Content "C:\computer.txt"

$Diskreport = $Servernames | % {
    Get-WmiObject Win32-LogicalDisk -Computername $_ -Filter "Drivetype=3" -ErrorAction SilentContinue |
        ? { ($_.freespace/$size) -le '0.7' }
}

[String]$body = $null
$DiskReport | % {
    $body += (Servername: "+$_.SystemName) + "'r'n"
    $body += (Drive Letter: "+$_.DeviceID.ToString()) + "'r'n"
    $body += (TotalCapacity (GB): "+((($_.size /1024) /1000) /1000).ToString()) + "'r'n"
    $body += (TotalCapacity (GB): "+((($_.Freespace /1024) /1000) /1000).ToString()) + "'r'n"
    $body += (TotalCapacity (GB): "+($Freespace /$_.size).ToString()) 
}

Send-MailMessage -Subject $Subject -Body $Body -From $from -To $to -SmtpServer $smtpserver -Port 587

1 个答案:

答案 0 :(得分:1)

字符串"'r'n"只是四个普通字符-单引号,r,单引号和n

如果要回车并在字符串中换行,请use a backtick`)逃逸rnas pointed out in the comments:< / p>

$body += "(Servername: " + $_.SystemName + ")`r`n" # and so on...

另一种方法是仅使用-join运算符通过[Environment]::NewLine连接所有行:

$bodyLines = @(
    "(Servername: $($_.SystemName))"
    "(Drive Letter: $($_.DeviceID.ToString()))"
    # etc...
)
$body += $bodyLines -join [Environment]::NewLine