如何使用CR LF换行符在Powershell中的一次调用中写入控制台和日志文件

时间:2010-11-12 23:11:32

标签: powershell newline

我有一个powershell脚本,我想写一个控制台并通过一次调用写入日志文件。

我这样做......

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

...效果很好,除了它生成的换行符是LF,这意味着我的日志在地球上的每个文本编辑器中看起来都很棒,除了记事本。

这就是我对此的看法......

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

...将CR写入每条消息的末尾,但它似乎没有写出这样的行......

&$ACommand | Write-Notepad

我不确定管道运营商期望的语法,但我非常感谢帮助。

2 个答案:

答案 0 :(得分:8)

试试这个:

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

Tee-Object会将管道对象的副本发送到文件或变量,并同时输出。

答案 1 :(得分:3)

这是我解决的解决方案......

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