60

I've compared two files using the following code:

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

How can I write the output of this to a new text file? I've tried using an echo command, but I don't really understand the syntax.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
bookthief
  • 2,375
  • 8
  • 35
  • 53

3 Answers3

97

Use the Out-File cmdlet

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

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

manojlds
  • 259,347
  • 56
  • 440
  • 401
  • 6
    What about STDOUT (info) vs. STDERR (error) messages? Will they both go to the out-file? – Jess Jul 23 '14 at 18:26
  • I know irrelevant but why the 'new' one makes it harder. What was wrong with >filename.txt – dvdmn Jul 26 '18 at 13:21
21

The simplest way is to just redirect the output, like so:

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

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

Matt
  • 4,792
  • 4
  • 30
  • 53
6

Another way this could be accomplished is by using the Start-Transcript and Stop-Transcript commands, respectively before and after command execution. This would capture the entire session including commands.

Start-Transcript

Stop-Transcript

For this particular case Out-File is probably your best bet though.

Aaron Krone
  • 192
  • 2
  • 11