Unix tail equivalent command in Windows Powershell

后端 未结 13 1722
攒了一身酷
攒了一身酷 2020-11-28 00:13

I have to look at the last few lines of a large file (typical size is 500MB-2GB). I am looking for a equivalent of Unix command tail for Windows Powershell. A f

13条回答
  •  星月不相逢
    2020-11-28 00:56

    Using Powershell V2 and below, get-content reads the entire file, so it was of no use to me. The following code works for what I needed, though there are likely some issues with character encodings. This is effectively tail -f, but it could be easily modified to get the last x bytes, or last x lines if you want to search backwards for line breaks.

    $filename = "\wherever\your\file\is.txt"
    $reader = new-object System.IO.StreamReader(New-Object IO.FileStream($filename, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
    #start at the end of the file
    $lastMaxOffset = $reader.BaseStream.Length
    
    while ($true)
    {
        Start-Sleep -m 100
    
        #if the file size has not changed, idle
        if ($reader.BaseStream.Length -eq $lastMaxOffset) {
            continue;
        }
    
        #seek to the last max offset
        $reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
    
        #read out of the file until the EOF
        $line = ""
        while (($line = $reader.ReadLine()) -ne $null) {
            write-output $line
        }
    
        #update the last max offset
        $lastMaxOffset = $reader.BaseStream.Position
    }
    

    I found most of the code to do this here.

提交回复
热议问题