How To Output To A File In Powershell With Out-File and Export-Csv Cmdlet?
Out-File is a cmdlet provided by Powershell core libraries. This cmdlet provides features to write created output into a file in the file system. In this tutorial we will look different ways to write output into a file with out-file cmdlet.
Write Into A File
One of the basic usage scenario of out-file is writing the output into a file without changing it. In this example we will write the output of
Get-Process command into a file named
process.txt by piping it. The file name can be specified as full path like
PS> Get-Process | Out-File process.txt
Append Into Existing File
If we just want to add new lines and do not want to remove existing data we should add new data with
-Append option like below.
PS> Get-Process | Out-File -Append process.txt
Write As CSV
We can write created output into a file is CSV format. CSV format delimits the columns with comma. We will use
Export-Csv cmdlet for this operation. This will take more time than raw write into file because row will be separated and each column will be delimited with command.
PS> Get-Process | Export-Csv test.txt
Write Both File and Console
Another most used feature is while writing output into a file printing in the console too. This will provide verbose information about output. We will use
Tee-Object which is inherited from Linux operating system.
In this example we get
dir command output into console and file named
PS> Dir | Tee-Object -f dirs.txt