powershell 取文件末尾行(ascill)

这是一个PowerShell函数,用于获取文件的最后几行。它遍历文件从后向前,仅适用于ASCII编码的文件。文章展示了如何使用该函数并提供了示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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 沙漠鱼 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zhaojun20002003/archive/2010/12/16/1908324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值