如何在 PowerShell 中同时写入控制台和日志文件并保留 CR LF

问题描述 投票:0回答:2

在 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

我不确定管道操作符需要什么语法,但我非常感谢帮助。

powershell logging newline
2个回答
12
投票

试试这个:

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

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


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 }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.