【问题标题】:Write-Host causes blank lines when redirected to a file重定向到文件时,Write-Host 会导致空行
【发布时间】:2021-06-03 07:01:37
【问题描述】:

sn-p

powershell { Write-Host "a"; Write-Host "b" } > test.txt; Write-Host "File contents:"; cat test.txt; rm test.txt

打印

a
b
File contents:
a


b


为什么文本文件中每个Write-Host调用后都有2个空白行?

更令人困惑的是当我们将所有流重定向到一个文件时的行为:

powershell { Write-Host "a"; Write-Host "b" } *> test.txt; Write-Host "File contents:"; cat test.txt; rm test.txt

打印

File contents:
a


b


a
b

现在该文件包含两次所有内容,首先是 2 个空行,然后是正常的。为什么文件现在包含所有内容两次?

【问题讨论】:

  • powershell " Write-Host 'a'; Write-Host 'b' "

标签: powershell powershell-5.1


【解决方案1】:

您的脚本执行以下操作:

Write-Host "a" 将a[CR][LF] 写入stdout。然后 powershell 出于某种原因* 添加[LF] 并将其作为元素存储在返回列表中。当它打印返回列表时,它将每个元素打印为[$value.toString()][CR][LF]。

这会让您的结果是Write-Host "a" 在输出中变为a[CR][LF][LF][CR][LF]。

* 需要调查。可能是if value from stdout and ends with [CR][LF]。同样,stdout 不应该在 powershell 中用作管道,因为 powershell 有它自己的对象管道。


Powershell 的Write-Host 并非设计用于捕获输出。取而代之的是Write-Output 命令或return。

除了Tee-Object 之外,没有good 内置命令可以将数据同时输出到文件和标准输出,但这有一些不同的作用。

您应该避免将 powershell 的 stdout 输出作为 stdin 用于其他命令,因为它可以包含您无法预料的 better-look enchancements、truncated parts 或 line wraps。如果无法避免,请使用Write-Output 并使用[void] 或.. | Out-Null 取消任何可能的输出。来自任何操作(如new-item)的所有未处理返回将传递给stdout


powershell {Write-Output "a" ;Write-Output "b"} > test.txt; Write-Host "File contents:"; cat test.txt; 
powershell {Write-Output "a" ;Write-Output "b"} | Out-File 'test.txt' ; Write-Host "File contents:"; cat test.txt; 
powershell { @('A';'B') | Out-File 'test.txt' } ; Write-Host "File contents:"; cat test.txt; 
powershell { @('A';'B') | Tee-Object -FilePath 'test.txt' | % { Write-Host "+ $_" } } | Out-Null ; Write-Host "File contents:"; cat test.txt; 
powershell {Write-Host "a" -NoNewline;Write-Host "b" -NoNewline} > test.txt; Write-Host "File contents:"; cat test.txt; 

【讨论】:

  • 根据docsWrite-Host写入信息流应该和其他任何重定向流一样好不是吗?
  • 另外,我使用Write-Host 明确写入控制台。我不希望这些条目最终进入管道!它们纯粹是记录语句。最后,我想将进程的每个输出重定向到日志文件。
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2015-09-20
相关资源
最近更新 更多