PowerShell: Write to File
Write to File
Set-Content
-
Write to file, with
value
parameter or piped input. If the file doesn't exit, it is 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 dotnet method:
[IO.File]::WriteAllText(filepath, content)
-
write content string to file at filepath.
Append to file
Add-Content
(aliasac
)-
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.This command is useful when you need to manipulate the string before sending to file.