2

テキスト ファイル (この場合はログ ファイル) の最後の n 行を取得する関数があります。

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()

    [....]
}

Write-Host でトラップすると、$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. 

したがって、最後の 2 つの完全な行が繰り返されます。最初にストリームリーダーをフラッシュしようとしましたが、オッズはありません。

これは少し混乱します。私は男子生徒の間違いを犯していると思いますが、どちらが間違っているのかわかりません。アイデアはありますか?

4

1 に答える 1

0

StreamReader から離れることができる場合は、この単純なコマンドを使用して、テキスト ファイルの最後の x 行を取得できます。

Get-Content C:\example.txt -Tail 10 
于 2013-02-25T14:58:10.700 に答える