Difference Between Set-Content and Out-File

Introduction

One of the key features of PowerShell is its ability to save data from scripts in files. In this blog post, we will compare two methods used to do this in PowerShell: Set-Content and Out-File.

What is Set-Content?

Set-Content is a built-in cmdlet in PowerShell that allows you to write content to a file. It is mainly used for creating files and writing the contents of variables into them. This cmdlet also has an alias sc which stands for set content. You can use this alias instead of the full name when you are scripting.

What is Out-File?

Out-File is another built-in cmdlet that creates and writes data to text files. It is similar to Set-Content but there are some important differences between the two commands that need to be taken into consideration when deciding which one to use in your script.

The most notable difference between these two commands is that Set-Content will overwrite existing content while Out-File allow us to append new content to existing file using -Append parameter. This means that if you want your script to add more information to an existing file without overwriting any existing data then you could use Out-File with -Append parameter instead of Set-Content.

Suppose you have existing file called example.txt contains below data:


This is old content

example file contains old content

We can replace existing content using below command:


Set-Content -Path .\example.txt -Value "This is new content"

example file contains new content

However, if we want to append the existing content we can use Out-File with -Append parameter like below:


Out-File -Path .\example.txt -InputObject "This is new content" -Append

append new content using out file with append parameter

Conclusion

Both Set-Content and Out-File can be used for writing data from scripts into files. However, there is a difference that Set-Content will replace the existing content with a new one while Out-File allows us to append a new content using -Append parameter.