Private/Split-ParsedFile.ps1
|
function Split-ParsedFile { <# .SYNOPSIS Splits a file into sequential binary parts of at most ChunkSizeMB megabytes. .DESCRIPTION Reads the source file in chunks and writes each chunk as a separate file inside a new subfolder named {BaseName}-Parts, following 7-zip multi-volume notation: {BaseName}.zip.001, {BaseName}.zip.002, ... The original file is left intact. .PARAMETER FilePath Full path to the file to split. .PARAMETER ChunkSizeMB Maximum size in megabytes for each part. Defaults to 14. .OUTPUTS [string[]] Ordered list of full paths to the created part files. #> param( [Parameter(Mandatory)] [string] $FilePath, [int] $ChunkSizeMB = 14 ) $chunkBytes = $ChunkSizeMB * 1024 * 1024 $dir = [System.IO.Path]::GetDirectoryName($FilePath) $baseName = [System.IO.Path]::GetFileNameWithoutExtension($FilePath) $partsDir = Join-Path $dir "$baseName-Parts" $null = New-Item -ItemType Directory -Path $partsDir -Force $partBase = Join-Path $partsDir $baseName $parts = [System.Collections.Generic.List[string]]::new() $buffer = New-Object byte[] $chunkBytes $reader = [System.IO.File]::OpenRead($FilePath) try { $partNum = 1 while ($reader.Position -lt $reader.Length) { $read = $reader.Read($buffer, 0, $chunkBytes) $partPath = '{0}.{1:D3}.zip' -f $partBase, $partNum $writer = [System.IO.File]::OpenWrite($partPath) try { $writer.Write($buffer, 0, $read) } finally { $writer.Dispose() } $parts.Add($partPath) $partNum++ } } finally { $reader.Dispose() } return ,$parts.ToArray() } |