代码片段
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调用后都有两个空行?
更令人困惑的是,当我们将所有流重定向到一个文件时的行为:
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现在这个文件包含了两次所有内容,第一次是两个空白行,然后是正常的。为什么这个文件现在包含了两次所有内容?
发布于 2021-03-05 05:45:49
您的脚本执行以下操作:
写入-主机"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 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; https://stackoverflow.com/questions/66478292
复制相似问题