To open and read files in powershell I use one of two methods:
Get-Content $path
or
[System.IO.File]::OpenRead($path)
While reading a log file that is in use by another process Get-Content doesn't seem to have any issues with it. Then again the powershell cmdlet is slow and uses more memory compared to .NET method. When I try to use .NET method however, I get the following error:
"The process cannot access the file 'XYZ' because it is being used by another process."
Q1: Why can't .net method access the file whilst powershell cmdlet can?
Q2: And how could I read the file with .net method? Since Get-Content is too slow for log files around 80 MB. I usually read just the last line with:
$line = ""
$lineBreak = Get-Date -UFormat "%d.%m.%Y "
$bufferSize = 30
$buffer = New-Object Byte[] $bufferSize
$fs = [System.IO.File]::OpenRead($logCopy)
while (([regex]::Matches($line, $lineBreak)).Count -lt $n) {
$fs.Seek(-($line.Length + $bufferSize), [System.IO.SeekOrigin]::End) | Out-Null
$fs.Read($buffer, 0, $bufferSize) | Out-Null
$line = [System.Text.Encoding]::UTF8.GetString($buffer) + $line
}
$fs.Close()
($line -split $lineBreak) | Select -Last $n
}
Author to original code on StackOverflow
Any help greatly appreciated !
PS! I'm using powershell 2.0 and can't kill the process that is using the file. Also I do not have write access to the file, just read.