在PowerShell中将输出写入文本文件

62

我使用以下代码比较了两个文件:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) 

我该如何将此输出写入新的文本文件?我尝试使用echo命令,但我不太了解其语法。

3个回答

99

使用 Out-File 命令

 Compare-Object ... | Out-File C:\filename.txt

可选地,将-Encoding utf8添加到Out-File中,因为默认编码对于许多用途来说并不是理想的。


6
标准输出(info)和标准错误(error)消息怎么处理?它们都会输出到输出文件吗? - Jess

24

最简单的方法就是直接重定向输出,像这样:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

>会覆盖输出文件(如果已存在)
>>会将新文本追加到输出文件末尾(如果已存在)。


8
这是cmd/dos方法。对于PowerShell,我认为使用Out-File更好。 - Austin T French
@AthomSfere,我同意。我还在学习PowerShell,老习惯难改。 :) - Matt
2
这也是Unix的方式,如果你被迫使用Windows,那就这样做吧。 - Ray Foss
5
也许并不过时?https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-7.1 - kitsu.eb

7
另一种实现方法是在命令执行之前和之后分别使用Start-TranscriptStop-Transcript命令。这将捕获包括命令在内的整个会话。
参考链接:Start-Transcript Stop-Transcript 对于这种情况,Out-File可能是最好的选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接