1

片段

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 个空行,然后是正常的。为什么文件现在包含所有内容两次?

4

1 回答 1

0

您的脚本执行以下操作:

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,但这会做一些不同的事情。

您应该避免使用 powershell 的stdout输出作为stdin其他命令,因为它可以包含better-look enchancementstruncated parts或者line wraps您不能期望。如果无法避免,请使用或Write-Output使任何可能的输出无效。来自任何操作(如,)的所有未处理的返回都将传递给[void].. | Out-Nullnew-itemstdout


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; 
于 2021-03-04T21:45:49.417 回答