powershell write to fileSet-Content is one of those core PowerShell cmdlets that I can’t do without. I still remember using VBscript before we could use PowerShell to write to a file. I remember always trying to remember what kind of object I needed to use and the method name. Was it FileSystemObject, FileObject or what? It was a pain! Also, even when I did recall the method name was CreateTextFile, I’d always forget to add True as the second argument.

Here’s an example of the monstrosity I’m talking about.

Compare that VBScript with this PowerShell:

Ready to stop reading and start learning about PowerShell, DSC, Windows Server, Sharepoint, IIS and dozens of other categories? If so, check out the hundreds of free technical demo screencasts available on the new, IT career development platform TechSnips.

Which one do you prefer? I’ll take the PowerShell way! The PowerShell way uses a single cmdlet called Set-Content. This cmdlet allows us to much more easily use PowerShell to write to a file. This PowerShell cmdlet is a built-in cmdlet that has one purpose; to write to a file. It may have some parameters here and there to change up that behavior a bit, but it’s solely focused on writing to a file. Not to be confused with Add-Content though since they are similar. Set-Content overwrites the entire file while Add-Content adds to a file. I learned that one the hard way multiple times when I first got started!

Creating a File/Overwriting a File

The Set-Content cmdlet is fairly simple. Below is a good example. This example shows that Set-Content can both create a file if it doesn’t exist or it can replace all of the contents inside of a pre-existing file.

Output to a File

One cmdlet that can output to a file is Out-File, but Set-Content can perform the same task albeit a little differently.

Perhaps you’d like to pull specific pieces of text from one text file and output lines to another file. By using Get-Content and Set-Content, you can make this happen. Maybe I’ve got a text file with one server and their status per line. I’d like to read each server’s status and output that to a file. Using Get-Content to read the file and Set-Content to write to file, it’s possible.

Set-Content is one of those core cmdlets that gets used constantly. It’s not fancy but works every time and is one you should have in your PowerShell bag of tricks.

For a full breakdown, check out the Set-Content Microsoft documentation.

%d bloggers like this: