You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell:如何阻止Tee-Object输出额外空行?

为什么Tee-Object写入日志会额外换行,而Add-Content不会?

问题场景

你创建日志文件的代码:

"Start of Log" | Out-File $ZipLog -encoding utf8 -force -ea silent

后续添加日志条目的代码:

Add-Content $ZipLog "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss")"
'Application installer:' | Tee-Object $ZipLog -Append
'More details 11 ...' | Tee-Object $ZipLog -Append
'More details 22 ...' | Tee-Object $ZipLog -Append
'More details 33 ...' | Tee-Object $ZipLog -Append

最终日志输出出现了多余空行:

2022-10-14 16:30:05
Application installer:

More details 11 ...

More details 22 ...

More details 33 ...

核心原因

这两个cmdlet的换行处理逻辑本质不同:

  • Add-Content:直接将传入的字符串内容追加到文件,默认只在内容末尾添加单个行终止符(通常是\r\n)。如果传入的字符串本身不带换行,最终日志里就是连续的单行内容。

  • Tee-Object:它依赖PowerShell的管道输出机制,内部调用Out-File来写入文件。Out-File在处理追加操作时,会先在新内容前额外插入一个行终止符,再加上字符串本身输出时自带的行终止符,相当于给每条内容前后都加了换行,最终就出现了日志里的空行。

简单说,Tee-Object是为管道输出设计的,默认会给每个输出对象添加额外的格式化换行,而Add-Content是纯粹的文件内容追加工具,行为更直白。

解决方法

如果需要同时输出到控制台和日志文件,又不想出现空行,可以替代Tee-Object,用以下方式实现:

# 先定义日志信息
$logMsg = 'Application installer:'
# 输出到控制台
Write-Host $logMsg
# 追加到日志文件
Add-Content $ZipLog $logMsg

或者通过调整Out-File的参数来配合Tee-Object:

'Application installer:' | Tee-Object -Variable temp | Out-File $ZipLog -Append -NoNewLine

内容的提问来源于stack exchange,提问作者YorSubs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:05:33