Search code examples
powershell

Store Entire Text File Contents in Variable


I'd like to use PowerShell to store the entire contents of a text file (including the trailing blank line that may or may not exist) in a variable. I'd also like to know the total number of lines in the text file. What's the most efficient way to do this?


Solution

  • To get the entire contents of a file:

    $content = [IO.File]::ReadAllText(".\test.txt")
    

    Number of lines:

    ([IO.File]::ReadAllLines(".\test.txt")).length
    

    or

    (gc .\test.ps1).length
    

    Sort of hackish to include trailing empty line:

    [io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count