Char(DesertFish)

A desert-fish want to go heaven.

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理


function Tail-Content([string[]] $Path,[int] $Last = 10,[string]$Newline=[Environment]::NewLine)
{

  $fs = $null
  $resolvedPaths = $Path     
  foreach ($rpath in $resolvedPaths)
  {
     $numLines = $Last
     $seekOffset = -1;
     $PathIntrinsics = $ExecutionContext.SessionState.Path
     if ($PathIntrinsics.IsProviderQualified($rpath))
     {
        $rpath = $PathIntrinsics.GetUnresolvedProviderPathFromPSPath($rpath)
     }
     Write-Verbose "Tail-Content processing $rpath"       
     $lines = New-Object 'System.Collections.Generic.List`1[System.String]'
     $line  = New-Object "System.Text.StringBuilder"
     $newlineIndex = $Newline.Length - 1
     $fs = New-Object "System.IO.FileStream" $rpath,"Open","Read"   
     while ($numLines -gt 0 -and ($fs.Length + $seekOffset -ge 0))
     {
           [void]$fs.Seek($seekOffset--, "End")
           $ch = $fs.ReadByte()
           if ($ch -eq 0 -or $ch -gt 127)
           {
               #throw "Tail-Content only works on ASCII encoded files"
           }
           # Chew up line termination characters
           if ($ch -eq $Newline[$newlineIndex])
           {
               if (--$newlineIndex -lt 0)
                {
                    $newlineIndex = $Newline.Length - 1
                    # Ignore the newline at the end of the file
                    if ($seekOffset -lt -($Newline.Length + 1))
                    {
                            $lines.Insert(0, $line.ToString())
                            $line = New-Object "System.Text.StringBuilder"
                            $numLines--
                     }
                 }
                    continue
            }
            [void]$line.Insert(0, [char]$ch)
      }
      if ($line.Length -gt 0)
      {
          $lines.Insert(0, $line.ToString())       
      }
      $lines
      if ($fs) { $fs.Close() }
  }
}

 

cls
cd "FileSystem::C:\archived\self\task\powershell\test"
$file ="FileSystem::C:\archived\self\task\powershell\test\OtherEnconding.txt"
#$file ="984MB.txt"
Tail-Content $file

posted on 2010-12-16 16:10  沙漠鱼  阅读(1111)  评论(0编辑  收藏  举报