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.
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!
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.
There are three file content related CmdLets that usually get used together and their names speak for themselves, they are:
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") -AsByteStreamThe issue was getting the data as a byte array. Note that this works with PowerShell Core.