Write output to a text file in PowerShell

PowershellFile Io

Powershell Problem Overview


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.

Powershell Solutions


Solution 1 - Powershell

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.

Solution 2 - Powershell

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.

Solution 3 - Powershell

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbookthiefView Question on Stackoverflow
Solution 1 - PowershellmanojldsView Answer on Stackoverflow
Solution 2 - PowershellMattView Answer on Stackoverflow
Solution 3 - PowershellAaron KroneView Answer on Stackoverflow