2013-02-25 19 views
2

我有一個函數來檢索文本文件的最後n行(在這種情況下,日誌文件):PowerShell的的StreamReader的ReadLine/ReadToEnd的讀取同一行多次

function Get-Tail([object]$reader, [int]$count = 10) { 

    $lineCount = 0 
    [long]$pos = $reader.BaseStream.Length - 1 

    while($pos -gt 0) 
    {  
     $reader.BaseStream.position=$pos 

     if ($reader.BaseStream.ReadByte() -eq 10) 
     { 
      $lineCount++ 
      if ($lineCount -ge $count) { break } 
     } 
     $pos-- 
    } 

    # tests for file shorter than requested tail 
    if ($lineCount -lt $count -or $pos -ge $reader.BaseStream.Length - 1) { 
     $reader.BaseStream.Position=0 
    } else { 
     $reader.BaseStream.Position = $pos+1 
    } 

    # debug 
    write-host $reader.readtoend() 

    [....] 
} 

套色寫主機,我覺得即$ pos是166(即良好EndOfStream之前)。

從這個輸出是:

2013/02/23 03:39:13 ERROR 2 (0x00000002) Accessing Source Directory \\[redacted] 
The system cannot find the file specified. ------------------------------------------------------------------------------- 

    Started : Sat Feb 23 03:39:13 2013 

    Source : [redacted] 
    Dest : [redacted] 

    Files : *.* 

    Options : *.* /FFT /V /TS /FP /NDL /TEE /S /E /COPY:DATS /SECFIX /PURGE /MIR /B /NP /XO /XN /XC /R:0 /W:0 

------------------------------------------------------------------------------ 

2013/02/23 03:39:13 ERROR 2 (0x00000002) Accessing Source Directory \\[redacted] 
The system cannot find the file specified. 

因此,最後兩行完全重複。我已經嘗試先沖洗流媒體播放器,沒有任何可能性。

這有點令人困惑。我以爲我這是小學生的錯誤,但不能工作了哪一個。請有任何想法嗎?

回答

0

如果你可以移動從StreamReader的路程比你可以使用這個簡單的命令來檢索的文本文件行的最後x號。

Get-Content C:\example.txt -Tail 10 
+1

我以前使用過它,但速度太慢,並且在處理某些日誌(在某些情況下運行到> 200MB)時會導致內存不足錯誤。後面的代碼解析日誌。所以,我真的覺得我確實需要使用的StreamReader修復它。 – 2013-02-25 16:11:02