How to Read a Text File as One String in PowerShell
Get-Content normally returns text line by line. Add -Raw when the caller needs a single string that retains the file's line breaks, such as a small template or JSON document.
Run a self-contained example
$demoFile = Join-Path ([IO.Path]::GetTempPath()) ('read-text-' + [guid]::NewGuid().ToString('N') + '.txt')
try {
Set-Content -LiteralPath $demoFile -Value "first`nsecond" -NoNewline -Encoding utf8 -ErrorAction Stop
$text = [string](Get-Content -LiteralPath $demoFile -Raw -Encoding utf8 -ErrorAction Stop)
$text.GetType().Name
$text -eq "first`nsecond"
} finally {
if (Test-Path -LiteralPath $demoFile) {
Remove-Item -LiteralPath $demoFile -ErrorAction Stop
}
}
The output is String and True. The explicit cast also gives an empty string when the file is empty. A missing or unreadable file still raises an error because the read uses -ErrorAction Stop.
Match the file's encoding
The example writes and reads UTF-8 deliberately. For an existing file, use its known encoding rather than guessing from its extension. A legacy Windows code-page file may decode incorrectly as UTF-8. If the data is binary, use a byte-oriented API instead of trying to repair corrupted text after decoding.
-LiteralPath treats brackets and other wildcard characters as part of the filename. This matters for names such as report[final].txt.
Choose a bounded read
-Raw loads the complete text into memory. For a large log, process lines or use -Tail for the relevant end of the file. Do not use a whole-file read merely to retrieve the last few events.
When migrating a VBScript ReadAll call, this command provides the corresponding whole-file text read. PowerShell owns the file handle during the operation, so the caller does not need a separate TextStream Close call.
References


Author: Herman Schoenfeld