-
-
Save santisq/0648b3992ca808aaa45e4c19f48117f3 to your computer and use it in GitHub Desktop.
Removes trailing null data from the end of a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Path = 'c:\temp\test.long' | |
$content = [Byte[]]::new(50MB) | |
[Array]::Copy( | |
[Byte[]][Char[]]'Hello world', | |
0, | |
$content, | |
10, | |
11 | |
) | |
[System.IO.File]::WriteAllBytes($Path, $content) | |
Get-Item $Path | Select-Object Length | |
Clean-File $Path | |
Get-Item $Path | Select-Object Length |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -AssemblyName System.Numerics | |
function Clean-File { | |
<# | |
.SYNOPSIS | |
Removes all trailing null content from the end of a file. | |
.DESCRIPTION | |
Removes all trailing null content from the end of a file. | |
Uses BigInteger to evaluate the content of the buffer. | |
#> | |
[CmdletBinding()] | |
param ( | |
# The file to trim. | |
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] | |
[Alas('FullName')] | |
[ValidateScript( { Test-Path $_ -PathType Leaf })] | |
[String]$Path, | |
# The initial size of the buffer. | |
[ValidateScript( { [Convert]::ToString($_, 2).Replace('0', '').Length -eq 1 } )] | |
[Int]$BufferSize = 1MB | |
) | |
process { | |
$Path = $pscmdlet.GetUnresolvedProviderPathFromPSPath($Path) | |
$currentBufferSize = $BufferSize | |
try { | |
$stream = [System.IO.FileStream]::new($Path, 'Open') | |
$null = $stream.Seek(0, 'End') | |
while ($currentBufferSize -gt 1) { | |
$buffer = [Byte[]]::new($currentBufferSize) | |
$null = $stream.Seek(-$currentBufferSize, 'Current') | |
$null = $stream.Read($buffer, 0, $buffer.Count) | |
if ([System.Numerics.BigInteger]::new($buffer) -ne 0) { | |
$currentBufferSize = $currentBufferSize / 2 | |
} else { | |
$null = $stream.Seek(-$currentBufferSize, 'Current') | |
} | |
} | |
$stream.SetLength($stream.Position) | |
$stream.Close() | |
} catch { | |
Write-Error -ErrorRecord $_ | |
} finally { | |
if ($stream) { | |
$stream.Close() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment