Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seek method not working in Powershell script

I´m trying to use the .net API to seek in a large data file. For some reason I am unable to make it work. Here is my code:

function check_logs{
  $pos = 8192
  $count = 1
  $path = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG.2'
  $br = 0
  $reader = [System.IO.File]::OpenText($path)
  $reader.DiscardBufferedData()
  $reader.BaseStream.Seek(0, [System.IO.SeekOrigin]::Begin)
    for(;;){
    $line = $reader.ReadLine()
    if($line -ne $null){$br = $br + [System.Text.Encoding]::UTF8.GetByteCount($line)}
    if($line -eq $null -and $count -eq 0){break}
    if($line -eq $null){$count = 0}
    elseif($line.Contains('  Error:')){
        Write-Host "$line  $br"
    }
}

}

If I use 0 as a parameter for the seek method it seeks from the beginning as expected but it also writes 0 out to the console before it writes the lines read. Example:

 0
 2011-08-31 09:26:36.31 Logon       Error: 17187, Severity: 16, State: 1.  4101
 2011-08-31 09:26:36.32 Logon       Error: 17187, Severity: 16, State: 1.  4489
 2011-08-31 09:26:38.25 Logon       Error: 17187, Severity: 16, State: 1.  4929
 2011-08-31 09:26:38.25 Logon       Error: 17187, Severity: 16, State: 1.  5304
 2011-08-31 09:26:43.75 Logon       Error: 17187, Severity: 16, State: 1.  6120

If I try to seek using 4096 instead of 0 it only writes out:

4096

I would have thought it would write out the same lines as the first one did apart from the first two.

Can someone see the problem? I had another question that got me to this. For further background see this

EDIT: Still trying to figure this out. Does anyone know where else I could try to find information regarding this problem? Is it possible to send questions to the Microsoft scripting guy?

Best regards

Gísli

like image 666
Gisli Avatar asked Sep 06 '25 01:09

Gisli


1 Answers

The Seek method returns the new position within the stream, which is why you are having a number printed out.

As to why you are not getting an output:

  1. Confirm the file is greater than 4K in size.
  2. Try printing out all lines, rather than just lines with the word "Error" in them. That might give you a clue
  3. StreamReader is a buffered wrapper around the base stream, so Seek and Position may not work quite like you expect. Consider http://geekninja.blogspot.com/2007/07/streamreader-annoying-design-decisions.html. Try adding in a call to $reader.DiscardBufferedData() before the seek.
like image 78
RB. Avatar answered Sep 08 '25 22:09

RB.