How To Write To A File In PowerShell?

PowerShell is a complete scripting language that provides different commands in order to write a file. There are commands like Out-File, Set-Content, and Add-Content in order to write into a file in different ways. In this tutorial, we examine these commands to write or append files by using the PowerShell environment.

Write File with Out-File Command

The Out-File is the most popular and official command to write a file. The Out-File is generally used with another command in order to redirect the output into the specified file. The -FilePath option is used to specify the file name and path to write the specified output. In the following example, we write the Get-Process command output into the file named ProcessList.txt .

PS> Get-Process | Out-File -FilePath ProcessList.txt

By default, the Out-File command overwrites the specified file and if there is the content inside it is deleted and new content is stored. The -Append option can be used to write to the specified file as an append by conserving the existing content.

PS> Get-Process | Out-File -Append -FilePath ProcessList.txt

Write File with Add-Content

Another option to write a file using PowerShell is the Add-Content command. As its name suggest the Add-Content command is used to append single or multiple lines of content into the specified file. The content we want to add is provided with the -Value option. Also, the -Path is used to specify the file name and path.

PS> Add-Content -Path c:\data.txt -Value "This is new line"

An alternative way to use the Add-Content is by running a command and putting the command output into the specified file. The -Value option is used to provide the command between brackets. In the following example, we run the Get-Process command and append all content to the file named “data.txt”.

PS> Add-Content -Path c:\data.txt -Value (Get-Process)

Write File with Redirect Operator (>)

PowerShell also provides the redirect or redirection operator in order to redirect some output into another command or file. We can simply write into a file by redirecting an output or content into the specified file. In the following example, we put some text into the file named “data.txt”.

PS> "Some content" > data.txt

Leave a Comment