Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write output to a text file in PowerShell

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.

like image 577
bookthief Avatar asked Aug 27 '13 15:08

bookthief


People also ask

How do you write data to a file in PowerShell?

You can also use PowerShell to write to file by appending to an existing text file with Add-Content Cmdlet. To append “This will be appended beneath the second line” to our existing file, first-file. txt, enter this command and press enter.

How do I create an output file in PowerShell?

There are a couple of ways to write the output of PowerShell to a file. The most common ways are to use the Out-File cmdlet or the redirection operator > . Other options are to use the Set-Content and Add-Content cmdlet.


2 Answers

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.

like image 176
manojlds Avatar answered Oct 10 '22 16:10

manojlds


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.

like image 25
Matt Avatar answered Oct 10 '22 15:10

Matt