Constructor
The constructor does not remove a file, rather, text written using the StreamWriter class is appended to the specified file (but see also the example below).
Write different encodings
The following simple
PowerShell script tries to demonstrate how a file in different
encodings:
UTF-8 with a
BOM, UTF-8 without a BOM and Latin 1.
Note that the script is encoded in Latin-1, so that its encoding is correctly determined in both, PowerShell 5.1 and 7.1 (see
encoding of PowerShell scripts). But this encoding causes this web page to render the
ä
of
'Bär'
with a question mark.
set-strictMode -version latest
$enc_utf8_with_bom = new-object System.Text.UTF8Encoding $true
$enc_utf8_without_bom = new-object System.Text.UTF8Encoding $false
$enc_1252 =[System.Text.Encoding]::GetEncoding(1252)
$out_utf8_with_bom = new-object System.IO.StreamWriter "$pwd/utf-8-with-bom.txt" , $false, $enc_utf8_with_bom
$out_utf8_without_bom = new-object System.IO.StreamWriter "$pwd/utf-8-without-bom.txt" , $false, $enc_utf8_without_bom
$out_1252 = new-object System.IO.StreamWriter "$pwd/1252.txt" , $false, $enc_1252
$out_utf8_with_bom.WriteLine('B�rlauch')
$out_utf8_without_bom.WriteLine('B�rlauch')
$out_1252.WriteLine('B�rlauch')
$out_utf8_with_bom.close()
$out_utf8_without_bom.close()
$out_1252.close()
format-hex "$pwd/utf-8-with-bom.txt"
format-hex "$pwd/utf-8-without-bom.txt"
format-hex "$pwd/1252.txt"
Appending text to a file
Some constructors of StreamWriter
allow to set the second parameter to true
so that text is appended to the file when re-opening it:
set-strictMode -version latest
$enc_utf8_without_bom = new-object System.Text.UTF8Encoding $false
#
# Create new StreamWriter. Setting second paramter to
# $true opens the stream in 'append' mode:
#
$str = new-object System.Io.StreamWriter "$pwd/file.txt", $true, $enc_utf8_without_bom
$str.WriteLine("This line was written at $( get-date -format 'yyyy-MM-dd HH-mm-ss (K)')" )
#
# For demonstration purposes: close and re-open stream:
#
$str.Close()
$str = new-object System.Io.StreamWriter "$pwd/file.txt", $true, $enc_utf8_without_bom
$str.WriteLine(' foo')
$str.WriteLine(' bar')
$str.WriteLine(' baz')
$str.Close()