How do I remove all newlines from a string in PowerShell?

EGr picture EGr · Jan 29, 2013 · Viewed 89.5k times · Source

This is the code I am using to parse my emails. If they match a specific date, I want to add them to a list of other emails, then make that into a flat file:

outfile = "C:\Temp\emails.csv"
$olFolderInbox = 6
$ol = new-object -comobject "Outlook.Application"
$mapi = $ol.getnamespace("mapi")
$inbox = $mapi.GetDefaultFolder($olFolderInbox)
$msgs = $inbox.Folders.Item("root")
$list1 = @()
foreach($message in ($msgs.items))
{
    if($message.ReceivedTime -gt $(get-date).adddays(-14))
    {
        $list1 += "$($message.Subject);$($message.ReceivedTime);$($message.Body.Replace("`n",", "))"
    }
}
if(Test-Path $outfile)
{
    Remove-Item $outfile
    Add-Content $outfile $list1
}
else
{
    Add-Content $outfile $list1
}

The problem I run into is that the replace statement on $message.Body.Replace("`n",", ") doesn't actually remove newlines, and the file doesn't get created appropriately. Is there a way to confirm that the entire contents of the body portion become a single line?

I have confirmed that the $message.body object is a string, so I'm not certain why this is not working.

Answer

noam picture noam · Feb 5, 2013

Commenters point to the return `r and maybe that special character should be replaced separately. Guessing this could be done with the .replace() method and some regex. Or more simply (and clumsily I admit) with another variable before your $list1 += line, such as:

$bod = $message.body -replace "`n",", " -replace "`r",", "

Overkill, but here's a small example from scratch. I'm suggesting you add $y to make it easier to manipulate the message body.

$x = new-object -type psObject
$x | add-member memburr1 -membertype noteproperty -value "no trouble here"
$x | add-member memburr2 -membertype noteproperty -value "uh `n oh `r spaghettio"

$y = $x.memburr2 -replace "`n",", " -replace "`r",", "

$z = @()
$z += "$($x.memburr1);$y"

If this doesn't help, I'd be curious what appears immediately before and after a problematic line break in the output.

EDIT: Or use the .replace() method twice:

$x.memburr2.replace("`n",", ").replace("`r",", ")