【问题标题】:Powershell StreamReader ReadLine / ReadToEnd reads same line multiple timesPowershell StreamReader ReadLine / ReadToEnd 多次读取同一行
【发布时间】:2013-02-25 14:51:19
【问题描述】:

我有一个函数可以检索文本文件(在本例中为日志文件)的最后 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. 

所以,最后两行是重复的。我已经尝试过先刷新流读取器,没有任何可能性。

这有点令人困惑。我想我犯了一个小学生错误,但不知道是哪一个。请问有什么想法吗?

【问题讨论】:

    标签: powershell streamreader powershell-3.0


    【解决方案1】:

    如果您可以远离 StreamReader,那么您可以使用这个简单的命令来检索文本文件中的最后 x 行。

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

    【讨论】:

    • 我以前用过,但它太慢了,并且在处理一些日志时会导致内存不足错误(在某些情况下会超过 200MB)。稍后的代码会解析日志。所以我真的认为我确实需要使用 StreamReader 来修复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多