PowerShell: Write to File

By Xah Lee. Date: . Last updated: .

Write to File

Set-Content
Write to file, with value parameter or piped input. If the file doesn't exit, it'll be created.
Set-Content "test.txt" -value "something"
dir | Set-Content "test.txt"
  • -NoNewline → do not add a CRLF at end of file.
  • -Encoding → default to utf8.

Here's a alternative, using .NET method:

[IO.File]::WriteAllText(file_path, content)
write content string to file at file_path.

Append to file

Add-Content (alias ac)
append content to file.

Output to File

Out-File
write output to file, from a piped input.
dir | Out-File "test.txt" -width 111222333 -NoNewLine
  • -width → max number of characters per line, any beyond is DELETED.
  • -NoNewline → do not add a CRLF at end of file.
  • -Encoding → default to utf8.
  • -Append → append to end.
  • -NoClobber → warn before overwrite.

To String

Out-String
convert input objects into one single string, or use Stream parameter to return array of strings.
Out-string is useful when you need to manipulate the string before sending to file.

PowerShell: Input/Output