PowerShell: Write to File

By Xah Lee. Date: .

2021-09-10 work in progress

Redirect Operator

Put content in a file:

"something" > myfile.txt

using the redirector operator is equivalent to piping to Out-File without any parameter. that is:

x > y

is same as

x | Out-File y


Note that, by default, the PowerShell redirect operator > creates files with UTF8NoBOM encoding, and lines are truncated to console window width. , and line ending uses Windows convention of "\r\n" (ASCII 13 and 10), also, a "\r\n" is added to end of file.


Append to file

"some more" >> myfile.txt

On unixes, the conventional file encoding is utf-8, and line ending uses "\n" (ASCII 10).

To create unix style output, use Out-File, like this:

"something" | Out-File -width 2999000 -NoNewLine myfile.txt

However, the line ending used is still "\r\n". To create unix line ending of just "\n", use:

… | Out-String | %{ $_.Replace("`r`n","`n") } | out-file

However, the end of the file will still contain a "\r".




Script Examples