Search code examples
powershellline-breaks

Avoid line breaks when using out-file


I'm getting a little frustrated on a little PowerShell script I'm writing.

Basically I loop through text files to check every line against an array of regular expression patterns. The result gets piped to the out-file cmdlet which appends it to another text file.

Get-ChildItem $logdir -Recurse -Include @('*.txt') | Get-Content | ForEach-Object { 
Select-String $patterns -InputObject $_ | Out-File $csvpath -Append -Width 1000 }

My problem is that I can't get out-file to omit those additional line breaks it creates in the file behind $csvpath (three after each line). I could use .NET framework classes to achieve the same thing but I'd rather stick to pure PowerShell


Solution

  • Why don't you use Add-Content?

    gci $logdir -rec *.txt | gc | select-string $pattern | add-content $csvpath
    

    You don't need to specify the width and -append switch, the file size is not doubled by default (although you can specify encoding) and it seems that there is no problem with the empty lines like you have.