PowerShell: How to read contents from text files without converting the lines into an array

Apparently, PowerShell’s get-content cmdlet automatically converts the contents of text files into an array of strings, splitting the contents at the line breaks (see Using the Get-Content Cmdlet). In many cases this is convenient:

Contents of file test.txt:

1
2
3

gc text.txt | % { write-host "line: " $_ } line: 1 line: 2 line: 3

However, if you need the file’s contents as an unchanged string (e.g. to keep line breaks the way they are when working with Unix/Linux line endings) this is not what you want. In this case, you can use the .NET method File.ReadAllText() (see File.ReadAllText Method:
[System.IO.File]::ReadAllText("text.txt") 1 2 3

Über Stefan

Polyglot Clean Code Developer

2 Kommentare

  1. You can even Use this to get the whole thing in one chunk:
    $Content = Get-Content test.txt -ReadCount 0

  2. Hi Peter, your code also returns an array and not the whole file content as a single String, or am I missing something here?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax