Creating Text Files

by Apr 13, 2009

PowerShell offers you a multitude of ways to write information to disk. Here's a quick overview.

1. You can use classic redirection:

"Hello" > $hometestfile.txt
"Append this" >> $hometestfile.txt
get-content $hometestfile.txt

This way, you have no control over encoding, though.

2. To control encoding, use Set-Content:

"Hello" | Set-Content $hometestfile.txt -Encoding Unicode
"Add this" | Add-Content $hometestfile.txt -Encoding Unicode
get-content $hometestfile.txt

Just make sure you use the same encoding for everything you add to a single file.

3. Or you can use Out-File:

"Hello" | Out-File $hometestfile.txt -encoding Unicode
"Add this" | Out-File $hometestfile.txt -encoding Unicode -append

4. Finally, you can use native applications and tools like fsutil. The next line creates a blank text file with a size of 1,000 bytes:

fsutil createNew $hometestfile.txt 1000

You should note, however, that tools like fsutil require administrator privileges.