Store the Output of a Command into a File
1. Problem
You want to redirect the output of a pipeline into a file.
2. Solution
To redirect the output of a command into a file, use either the Out-File cmdlet or one of the redirection operators.
Out-File:
      Â
       Get-ChildItem | Out-File unicodeFile.txt
       Get-Content filename.cs | Out-File -Encoding ASCII file.txt
       Get-ChildItem | Out-File-Width 120 unicodeFile.cs
       Get-ChildItem > files.txt
       Get-ChildItem 2> errors.txt
3. Discussion
The Out-File cmdlet and redirection operators share a lot in common—and for the most part, you can use either. The redirection operators are unique because they give the greatest amount of control over redirecting individual streams. The Out-File cmdlet is unique primarily because it lets you easily configure the formatting width and encoding.
The default formatting width and the default output encoding are two aspects of output redirection that can sometimes cause difficulty.
The default formatting width sometimes causes problems because redirecting PowerShell-formatted output into a file is designed to mimic what you see on the screen. If your screen is 80 characters wide, the file will be 80 characters wide as well. Examples of PowerShell-formatted output include directory listings (that are implicitly for-matted as a table) as well as any commands that you explicitly format using one of the Format-*set of cmdlets. If this causes problems, you can customize the width of the file with the—Width parameter on the Out-File cmdlet.
The default output encoding sometimes causes unexpected results because PowerShell creates all files using the UTF-16 Unicode encoding by default. This allows PowerShell to fully support the entire range of international characters, cmdlets, and output. Although this is a great improvement to traditional shells, it may cause an unwanted surprise when running large search and replace operations on ASCII source code files, for example. To force PowerShell to send its output to a file in the ASCII encoding, use the—Encoding parameter on the Out-File cmdlet.
Tags: cmd, cmdlet, export, export file, output, powershell, store command
