Skip to content

Instantly share code, notes, and snippets.

@santisq
Forked from indented-automation/Clean-File-Demo.ps1
Created June 15, 2022 16:04
Show Gist options
  • Save santisq/0648b3992ca808aaa45e4c19f48117f3 to your computer and use it in GitHub Desktop.
Save santisq/0648b3992ca808aaa45e4c19f48117f3 to your computer and use it in GitHub Desktop.
Removes trailing null data from the end of a file
$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
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