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.

It is worth adding that I have used this with both PowerShell 4 and PowerShell Core 6 writing to the same file, they are not compatible!

Creating Files

There are at least two ways to create an empty file, as follows:
Set-Content -Path "TestFile.txt" -Value $null
New-Item -Path "TestFile.txt" | Out-Null
From this point you can Add-Content, as needed.

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 objects to a file, either creating or replacing the file
  • Add-Content: simply add content to an existing file
  • Clear-Content: don't delete the file, just empty it
Fortunately they are simple to use.

When needing to write data to a file in "binary" mode then I used the following technique.

Set-Content -Path $OutputFile -Value (New-Object System.Text.UTF8Encoding).GetBytes("Hello World") -AsByteStream
The issue was getting the data as a byte array. Note that this works with PowerShell Core.