Search notes:

PowerShell cmdLet Out-File

out-file redirects the objects of a pipeline into a file.
Since PowerShell 5.1, the redirection operators are basically aliases for out-file. However, with the parameters that out-file provides, it is more flexible than the redirection operators.
Unless the -append option is used, the file is newly created or overwritten.
With the -append option, the file is created if it does not exist, then the objects are appended to the file.

Creating vs writing to a new file

By default, out-file creates a file (as does the redirection operator >). Using -append, content is added to a file (if the file exists). Otherwise, -append also creates the file.
'some text' | out-file  xyz.log
'more text' | out-file  xyz.log -append

Preventing accidental creation of a file

The accidential creation of a file can be prevented with -noClobber
'foo bar baz' | out-file xyz.log -noClobber

Write a file line by line

'A' | out-file         file.txt
'B' | out-file -append file.txt
'C' | out-file -append file.txt

format-hex file.txt
Github repository about-PowerShell, path: /cmdlets/file/out/write-file.ps1
The behaviour of out-file seems to have changed between PowerShell version 5.1 and 7.0. With 5.1, the script prints
           Path: …

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   FF FE 41 00 0D 00 0A 00 C3 00 1E 20 0D 00 0A 00  .þA.....Ã.. ....
00000010   42 00 0D 00 0A 00                                B.....
With 7.0, the script prints
                       Path: …

                       00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000000000000000   41 0D 0A C3 84 0D 0A 42 0D 0A                    A..Ä..B..
The difference is that the 5.1 version writes the file in UTF16, LE, with a BOM (Byte Order mark) while the 7.0 version writes the file in UTF-8.

-Encoding

The parameter -encoding allows to specify the encoding with which text is written to the file:
'abc' | out-file -encoding ascii abc.txt

-NoNewLine

'foo', 'bar', 'baz' | out-file -encoding ascii -noNewLine  without-new-line.txt
'foo', 'bar', 'baz' | out-file -encoding ascii                with-new-line.txt

format-hex without-new-line.txt
#
#  66 6F 6F 62 61 72 62 61 7A

format-hex with-new-line.txt
#
#  66 6F 6F 0D 0A 62 61 72 0D 0A 62 61 7A 0D 0A
Github repository about-PowerShell, path: /cmdlets/file/out/noNewLine-pipeline.ps1

See also

The redirection operators (>, >>, 2>, 2>>, 2>&1)
Powershell command noun: file
PowerShell command verb: out
set-content
out-file belongs to the cmdlets with the -encoding parameter.
The .NET class System.IO.StreamWriter

Index