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.

To Pipeline

Write-Output (alias echo , write)
sends objects to the pipeline. If it is the last command, send them to screen.
Use -NoEnumerate to make the output as one single string.
Note, if the out-string command is wrapped in parentheses, the parentheses force enumeration.

To Screen

Write-Host
print to screen. Useful for user prompt.

Auto to Screen

Out-Host
send output to screen. Out-Host is automatically appended to every command that is executed. To suppress it, pipe to out-null. More efficient way is to assign it to $null. e.g. $null = mkdir dirName

PowerShell

How-to

Advanced

Script Examples