Redirection Operators > and >> in Windows PowerShell

Jul. 11, 2024

For Windows PowerShell, > and >> are redirection operators1 used to redirect output2:

By default, PowerShell sends output to the PowerShell host. Usually this is the console application. However, you can redirect the output to a text file and you can redirect error output to the regular output stream.

You can use the following methods to redirect output:

  • Use the Out-File cmdlet, ……
  • Use the Tee-Object cmdlet, ……
  • Use the PowerShell redirection operators. Redirecting the output of a PowerShell command (cmdlet, function, script) using the redirection operator (>) is functionally equivalent to piping to Out-File with no extra parameters. PowerShell 7.4 changed the behavior of the redirection operator when used to redirect the stdout stream of a native command.

……

>: Send specified stream to a file.

>>: Append specified stream to a file.

>&1: Redirects the specified stream to the Success stream.

That is, redirection operators redirect output that would be printed in PowerShell host to a file instead (which also means that those outputs don’t appear on PowerShell host any more).

Take outputting Python package list to .txt file as an example. I create a new Python virtual environment using venv module3, and new two text files in which, i.e. packages1.txt and packages2.txt, whose content are the same:

1
2
Package list

NOTE: There is a empty line intentionally put at the end of the file.

Then, I use operators > and >> to redirect output to packages1.txt and packages2.txt, respectively.

(1) By >

1
pip list > packages1.txt

packages1.txt

1
2
3
4
5
Package    Version
---------- -------
pip        24.0
setuptools 65.5.0

(2) By >>

1
pip list >> packages2.txt

packages2.txt

1
2
3
4
5
6
Package list
Package    Version
---------- -------
pip        24.0
setuptools 65.5.0

As expected, operator > overwrites the original file, while >> appends output at the end of the original file.


References