powershellloggingnewline

How to write to console and log file simultaneously in PowerShell preserving CR LF


In a PowerShell script I want to write to the console and a log file simultaneously.

I did this:

Start-Transcript -Path $TargetDir\Log.log
Write-Host "Stuff"

which works great, except that the newlines it generates are LF, which means my logs look great in literally every text editor except Notepad.

That's what I did:

function global:Write-Notepad
(
    [string] $Message,
    [string] $ForegroundColor = 'Gray'
)
{
    Write-Host "$Message`r" -ForegroundColor $ForegroundColor
}

which writes a CR to the end of every message, but it doesn't seem to write out lines like this.

&$ACommand | Write-Notepad

I'm not sure what syntax the piping operator expects, but I would greatly appreciate help.


Solution

  • Here's the solution I settled on...

    # This method adds a CR character before the newline that Write-Host generates.
    # This is necesary, because notepad is the only text editor in the world that
    # doesn't recognize LF newlines, but needs CR LF newlines.
    function global:Write-Notepad
    (
        [string] $Message,
        [string] $ForegroundColor = 'Gray'
    )
    {
        Process
        {
            if($_){ Write-Host "$_`r" }
        }
        End
        {
            if($Message){ Write-Host "$Message`r" -ForegroundColor $ForegroundColor }
        }
    }