PoshCode Logo PowerShell Code Repository

Get-Tail.ps1 by BSonPosh 6 years ago
View followups from ScriptQuest | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/87"></script>download | new post

Tails a File

  1. # Name: Get-Tail.ps1
  2. # Author: William Stacey
  3. # Created: 02/22/2007
  4. # Description: Gets the last N lines of a file. Does scan from end-of-file so works on large files. Also has a loop flag that prompts for refresh.
  5.  
  6. function Get-Tail([string]$path = $(throw "Path name must be specified."), [int]$count = 10, [bool]$loop = $false)
  7. {
  8.         if ( $count -lt 1 ) {$(throw "Count must be greater than 1.")}
  9.         function get-last
  10.         {
  11.                 $lineCount = 0
  12.                 $reader = new-object -typename System.IO.StreamReader -argumentlist $path, $true
  13.                 [long]$pos = $reader.BaseStream.Length - 1
  14.  
  15.                 while($pos -gt 0)
  16.                 {
  17.                         $reader.BaseStream.Position = $pos
  18.                         if ($reader.BaseStream.ReadByte() -eq 10)
  19.                         {
  20.                                 if($pos -eq $reader.BaseStream.Length - 1)
  21.                                 {
  22.                                         $count++
  23.                                 }
  24.                                 $lineCount++
  25.                                 if ($lineCount -ge $count) { break }
  26.                         }
  27.                         $pos--
  28.                 }
  29.                
  30.                 if ($lineCount -lt $count)
  31.                 {
  32.                         $reader.BaseStream.Position = 0
  33.                 }
  34.                
  35.                 while($line = $reader.ReadLine())
  36.                 {
  37.                         $lines += ,$line
  38.                 }
  39.                
  40.                 $reader.Close()
  41.                 $lines
  42.         }
  43.  
  44.         while(1)
  45.         {
  46.                 get-last
  47.                 if ( ! $loop ) { break }
  48.                 $in = read-host -prompt "Hit [Enter] to tail again or Ctrl-C to exit"
  49.         }
  50. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me