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

URL dieses Beitrags: http://blog.stefan-macke.com/2012/06/12/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

Kommentare zu diesem Beitrag

  1. Gravatar Peter Kriegel
    Am 3. Juli 2012 um 18:08 Uhr

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

  2. Gravatar Stefan
    Am 3. Juli 2012 um 19:19 Uhr

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

Einen Kommentar schreiben

XHTML: Diese Tags sind erlaubt: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>