CRLF从作为电子邮件正文发送的多行字符串中删除

时间:2015-01-16 12:10:53

标签: powershell powershell-v2.0

我从MSSQL HR数据库中提取数据并运行foreach循环,并将行集中的各个字段与用户的AD属性进行比较。这很好用。在这个循环中,当我继续记录我正在为每个用户做的事情时,我也会附加到字符串,并且还记录错误消息。例如:

foreach ($user in $users) {
    # Try and find the AD User
    $ADUser = $(try {Get-ADUser $user.SamAccountName -Properties Office,OfficePhone,MobilePhone,Department,Title,City,PostalCode,StreetAddress} catch {$null})

    #Check if we found it
    if ($ADuser -ne $null) {
        $ADUpdated = $false

        #We did so check the HR data too before we try and use it
        if (-Not ([string]::IsNullOrEmpty($user.Title))) {
            if (($user.Title -ne $ADUser.Title)) { #Check if we need to update 
                # Update the Job Title attribute
                Write-Verbose ("Updating Job Title to " + $user.Title + " for " + $user.SamAccountName + " (" + $user.DisplayName + ")")
                Set-ADUser $user.SamAccountName -Title $user.Title
                $messagebody += "Updating Job Title to " + $user.Title + " for " + $user.SamAccountName + " (" + $user.DisplayName + ")" + " `r`n"
                $ADtitleUpdated++
                $ADUpdated = $true
            }
        } else {
            #HR Database is wrong
            $HRnoTitle++
            $messagebody += "Missing Job Title in HR Record for " + $user.DisplayName  + " `r`n"
            Write-Warning ("Missing Job Title in HR Record for " + $user.DisplayName)
            if ($ADUpdated) {$ADrecordsUpdated++}
        }
    else {
        #User is missing in AD but Exists in HR Database
        $ADmissing++
        Write-Warning ($user.SamAccountName + " (" + $user.DisplayName + ")" + " exists in HR Database but doesn't in AD!")
        $messagebody += $user.SamAccountName + " (" + $user.DisplayName + ")" + " exists in HR Database but doesn't in AD!`r`n"
    }

因此$messagebody有一个多行字符串,告诉我HR DB中的用户记录是否存在问题,或者是否缺少任何AD帐户。当我用Write-Host打印出来时,我得到了正确的信息。但是当我通过Send-MailMessage发送时,CRLF丢失了。我该怎么做才能保留CRLF?邮件客户端是Outlook 2010。

1 个答案:

答案 0 :(得分:0)

@Matt是对的。根据{{​​3}},我只需要在输出中添加一些标点符号。我将" `r`n"更改为". `r`n"并确保我的Here-Strings中的所有行都以标点符号结束。