How can I remove carriage returns from the text file using Powershell?

advertisements

I'm outputting the contents of a directory to a txt file using the following command:

$SearchPath="c:\searchpath"
$Outpath="c:\outpath"

Get-ChildItem "$SearchPath" -Recurse | where {!$_.psiscontainer} | Format-Wide -Column 1'
| Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200

What I end up with when I do this is a txt file with the information I need, but it adds numerous carriage returns I don't need, making the output harder to read.

This is what it looks like:

    c:\searchpath\directory

name of file.txt

name of another file.txt

    c:\searchpath\another directory

name of some file.txt

That makes a txt file that requires a lot of scrolling, but the actual information isn't that much, usually a lot less than a hundred lines.

I would like for it to look like:

  c:\searchpath\directory
nameoffile.txt
  c:\searchpath\another directory
another file.txt

This is what I've tried so far, not working

$configFiles=get-childitem "c:\outpath\*.txt" -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "'n", ""} |
Set-Content $file.PSPath
}

I've also tried 'r but both options leave the file unchanged.

Another attempt:

Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line}'
| Set-Content -Path c:\outpath\contents2.txt

When I run that string without the Set-content at the end, it appears exactly as I need it in the ISE, but as soon as I add the Set-Content at the end, it once agains carriage returns where I don't need them.

Here's something interesting, if I create a text file with a few carriage returns and a few tabs, then if I use the same -replace script I've been using, but uset to replace the tabs, it works perfect. Butr and n do not work. It's almost as though it doesn't recognize them as escape characters. But if I addr and `n in the txt file then run the script, it still doesn't replace anything. Doesn't seem to know what to do with it.


Set-Content adds newlines by default. Replacing Set-Content by Out-File in your last attempt in your question will give you the file you want:

Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line} |
Out-File -FilePath c:\outpath\contents2.txt