- <#*,:&cls
- @echo off
- cd /d "%~dp0"
- powershell -NoProfile -ExecutionPolicy RemoteSigned -Command ". ([ScriptBlock]::Create((Get-Content -LiteralPath \"%~0\" -ReadCount 0 | Out-String ))) "
- pause
- exit /b
- #>
- # 功能:删除文件的最后N行
- # 大文件
- $file = "largeFile.txt"
- # 最后N行
- $lastN = 7
- # 换行分割符
- $charDelims = 13
-
- try {
- $stream1 = New-Object System.IO.FileStream -ArgumentList @($file, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
- $pos = $stream1.Seek(0, [System.IO.SeekOrigin]::End)
- $ctrLines = 0
- while ($ctrLines -lt $lastN -and $pos -gt 0) {
- $pos = $stream1.Seek(-1, [System.IO.SeekOrigin]::Current)
- $byte = $stream1.ReadByte()
- if ($byte -eq $charDelims) {
- $ctrLines++
- }
- $pos = $stream1.Seek(-1, [System.IO.SeekOrigin]::Current)
- }
- $stream1.SetLength($pos)
- } catch {
- $_ | Write-Host -ForegroundColor Red
- } finally {
- if ($stream1) {
- $stream1.Dispose()
- }
- }
复制代码
|