Read text files that are in use

by Apr 14, 2011

Get-Content can read text files only line-by-line. Use .NET directly if you need the exact content of a text file as one large text. Here is how you read the entire text file in one line:

PS > [System.IO.File]::ReadAllText("c:\sometextfile.txt")

 

However, this would open the file for exclusive read access. No other application can access the file while you are using it, and you cannot read files that are in use by someone else. To read files non-exclusively (like system logs), you can use this:

 

$file = [System.io.File]::Open("$env:windir\windowsupdate.log", 'Open', 'Read', 'ReadWrite')
$reader = New-Object System.IO.StreamReader($file)
$text = $reader.ReadToEnd()
$reader.Close()
$file.Close()

Open() will tell Windows that you want to open a file for reading and
to  allow others to access the file for reading and writing while you
are using it. This will allow the file to be fully accessible for others
and you can now read files that are in use by other applications.

 

Twitter This Tip!
ReTweet this Tip!