How to write to console and log file in one call in Powershell with new CR LF lines

I have a powershell script, and I want to write to the console and write to the log file with one call.

I did it...

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

... which works great, except that the new lines it creates are LF, which means that my logs look great in every text editor on earth except notepad.

Here is what I have for this ...

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

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

&$ACommand | Write-Notepad

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

+3
source share
2 answers

, ...

# 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 }
    }
}
+3

:

& $ACommand | Tee-Object -FilePath $TargetDir\Log.log | Write-Host

Tee-Object .

+5

Source: https://habr.com/ru/post/1774630/


All Articles