Writing to Files

Writing to files is an important part of all scripting languages and really all development languages. However I find with scripting languages it is more important as they are used for simple tasks and often as scheduled jobs. So here is some information on useful PowerShell CmdLets for file handling.

Out-File

This is a pretty basic one, it really just does what standard output redirection did in DOS batch scripts, for example:
Get-ChildItem | Out-File Listing.txt which simple outputs a directory listing to a file.
There are a few extra options like "-append" but it is not the most flexible CmdLet.

The "Contents"

There are three file content related CmdLets that usually get used together and their names speak for themselves, they are:

  • Get-Content: get the contents of a file, reading lines into a collection of objects
  • Set-Content: write strings or obects to a file, either creating or replacing the file
  • Add-Content: simply add content to an existing file
Fortunately they are simple to use.