开发者

How do I write to the console and a log file in one call in Powershell with CR LF newlines

开发者 https://www.devze.com 2023-01-24 16:21 出处:网络
I have a powershell script and I want to write to a console and write to a log file with one call. I was doing this...

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

I was doing 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 every text editor on earth, except for notepad.

Here's 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 every message, but it doesn't seem to write out lines like this...

&$ACommand | Write-Notepad

I'm n开发者_JS百科ot sure what syntax the piping operator expects, but I would greatly appreciate help.


Try this:

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

Tee-Object will send a copy of the pipeline objects to a file or a variable, and output at the same time.


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 }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消