PowerShell provides the
Out-File command in order to send output into a file. The Out-File command is very similar to the Linux output redirection operator
> . The Out-File comand can be also used to append files or set encoding etc.
Save Output To File
The Out-File command is mainly used to save output into a file. The file name or path can be specified with the
-FilePath . In the following example, we save the command output into the file named “ProcessList.txt”. the
| pipe operator is used to redirect the command output into the Out-File command.
PS> Get-Process | Out-File -FilePath ProcessList.txt
Append Output To File
By default, the Out-File creates the specified file and puts content into it. If the file is already created existing file content is overwritten. We can prevent overwriting and append output into the existing file content with the
PS> Get-Process | Out-File -Append -FilePath ProcessList.txt
Remove New Line Characters
The output may contain different control characters like the new line. If we need to remove new line characters and add them to the file as a single line we can use the
-NoNewline option like below.
PS> Get-Process | Out-File -NoNewline -FilePath ProcessList.txt
If we are adding command output into an existing file and the destination file is read-only we should use the
-Force option to add new content.
PS> Get-Process | Out-File -Append -Force -FilePath ProcessList.txt
Another useful feature of the Out-File is setting the encoding. We can set the output encoding while writing into the file. The
-Encoding is used to set encoding. In the following example, we set the encoding as
PS> Get-Process | Out-File -Encoding utf8 -FilePath ProcessList.txt
The following encoding types are supported by the Out-File command.