← 返回文章

大文件切割与还原:7-Zip 分卷和 PowerShell 流式脚本

从 Windows 缺少 split 命令的问题出发,用固定缓冲区、连续分片清单和 SHA256 校验可靠地拆分与还原文件。

大文件超出上传限制时,可以分卷压缩,也可以按原始字节拆分。后者不会压缩内容,还原后的文件必须与原文件逐字节相同;拆分本身也不会加密文件。

Windows 先选对工具

Windows 默认没有 GNU 的 split 命令。在普通 CMD 或 PowerShell 中提示找不到命令,是因为没有安装相应工具。不要继续照搬 Linux 命令。

临时传文件时,可以使用 7-Zip 官方版本:在“添加到压缩包”中选择 7z 格式并设置分卷大小,例如 1000M。收齐所有分卷并放在同一个目录后,从第一个 .7z.001 文件开始解压。7z 分卷和 WinRAR 的 .part1.rar 是不同格式,文件名不能混用。创建期间不要提前移动尚未完成的卷。

下面的脚本适合不需要压缩、希望自己控制分片大小与校验流程的情况。

PowerShell 7:按清单切割和合并

把以下完整代码保存为 FileParts.ps1。脚本使用 1 MiB 缓冲区,不把整个分片一次性读进内存;分片大小可以是 1 GiB,但内存缓冲区仍是 1 MiB。它按清单记录顺序,避免 part1、part10、part2 的字符串排序问题。

function Split-LargeFile {
    param(
        [Parameter(Mandatory)][string]$Source,
        [Parameter(Mandatory)][string]$PartsDirectory,
        [ValidateRange(1, [long]::MaxValue)][long]$PartSize = 1GB
    )
    $ErrorActionPreference = 'Stop'
    $sourcePath = (Resolve-Path -LiteralPath $Source).ProviderPath
    $partsPath = [IO.Path]::GetFullPath($PartsDirectory)
    if (Test-Path -LiteralPath $partsPath) { throw '分片目录必须是新目录。' }
    $inputStream = [IO.File]::OpenRead($sourcePath)
    try {
        [IO.Directory]::CreateDirectory($partsPath) | Out-Null
        $sha = [Security.Cryptography.SHA256]::Create()
        try { $hash = [Convert]::ToHexString($sha.ComputeHash($inputStream)) }
        finally { $sha.Dispose() }
        $inputStream.Position = 0
        $buffer = [byte[]]::new(1MB)
        $parts = [Collections.Generic.List[object]]::new()
        while ($inputStream.Position -lt $inputStream.Length) {
            $name = 'part{0:D6}.bin' -f ($parts.Count + 1)
            $length = [Math]::Min($PartSize, $inputStream.Length - $inputStream.Position)
            $part = [IO.File]::Open((Join-Path $partsPath $name), 'CreateNew', 'Write', 'None')
            try {
                $remaining = $length
                while ($remaining -gt 0) {
                    $read = $inputStream.Read($buffer, 0, [int][Math]::Min($buffer.Length, $remaining))
                    if ($read -eq 0) { throw '源文件提前结束。' }
                    $part.Write($buffer, 0, $read)
                    $remaining -= $read
                }
            } finally { $part.Dispose() }
            $parts.Add([ordered]@{ name = $name; length = $length })
        }
        [ordered]@{
            version = 1; length = $inputStream.Length; sha256 = $hash; parts = @($parts.ToArray())
        } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $partsPath 'manifest.json') -Encoding utf8
    } finally { $inputStream.Dispose() }
}

function Join-LargeFile {
    param(
        [Parameter(Mandatory)][string]$PartsDirectory,
        [Parameter(Mandatory)][string]$Output
    )
    $ErrorActionPreference = 'Stop'
    $partsPath = (Resolve-Path -LiteralPath $PartsDirectory).ProviderPath
    $manifest = Get-Content -LiteralPath (Join-Path $partsPath 'manifest.json') -Raw | ConvertFrom-Json
    if ($manifest.version -ne 1 -or $manifest.sha256 -notmatch '^[0-9A-Fa-f]{64}$') { throw '清单格式错误。' }
    $index = 0
    $total = [long]0
    foreach ($entry in $manifest.parts) {
        $index++
        if ($entry.name -cne ('part{0:D6}.bin' -f $index) -or $entry.length -le 0) { throw '分片清单顺序或长度错误。' }
        $file = Get-Item -LiteralPath (Join-Path $partsPath $entry.name)
        if ($file.PSIsContainer -or $file.Length -ne $entry.length) { throw "分片缺失或大小不符:$($entry.name)" }
        $total += $file.Length
    }
    if ($total -ne $manifest.length) { throw '清单总长度不符。' }
    $outputPath = [IO.Path]::GetFullPath($Output)
    # CreateNew 遇到已有文件会报错,不会覆盖原文件。
    $outputStream = [IO.File]::Open($outputPath, 'CreateNew', 'Write', 'None')
    try {
        foreach ($entry in $manifest.parts) {
            $part = [IO.File]::OpenRead((Join-Path $partsPath $entry.name))
            try { $part.CopyTo($outputStream, 1MB) }
            finally { $part.Dispose() }
        }
    } finally { $outputStream.Dispose() }
    $actual = (Get-FileHash -LiteralPath $outputPath -Algorithm SHA256).Hash
    if ($actual -ne $manifest.sha256) { throw 'SHA256 校验失败;输出文件不完整或损坏,请勿使用。' }
    "还原成功,SHA256 = $actual"
}

运行示例(在 PowerShell 7 中执行,先把路径替换为自己的文件):

. .\FileParts.ps1

Split-LargeFile -Source 'D:\Transfer\backup.bak' `
    -PartsDirectory 'D:\Transfer\backup-parts' -PartSize 1GB

Join-LargeFile -PartsDirectory 'D:\Transfer\backup-parts' `
    -Output 'D:\Transfer\backup-restored.bak'

PartsDirectory 必须是新目录;输出文件的父目录必须存在,输出文件本身必须不存在。传输时同时带上所有 part*.bin 和 manifest.json。空文件会得到不含分片的清单,也能正确还原。

脚本使用 PowerShell 7 所在现代 .NET 的 Convert.ToHexString。Windows PowerShell 5.1 不能原样运行;不要为了执行脚本而全局关闭组织的执行策略。如果电脑要求签名,应按现有管理要求运行。

为什么要这样处理

容易忽略的问题 本例的处理
把 1 GB 分片整个读入内存 用小缓冲区流式读写。
Read 不一定一次读满 根据实际返回字节数循环,直到分片长度写完。
文件名排序导致错序 清单给出确定顺序并检查连续编号。
合并时缺片或长度不对 创建输出前检查所有分片和总长度。
输出同名覆盖原文件 使用 FileMode.CreateNew,已有文件会报错。
同大小的内容损坏 合并后校验 SHA256。

关于流读取可能返回少于请求长度的行为,可参考 FileStream.Read;关于已有文件保护,可参考 FileMode.CreateNew。

拆分会先读一遍源文件计算 SHA256,再从头切片,因此需要两遍读取时间。合并期间不要编辑清单或分片。若写入失败或 SHA256 不匹配,输出路径可能留有不完整文件,必须重新核验后处理,不能直接用于数据库还原。

SHA256 用于发现传输和存储损坏;如果文件与清单都可能被第三方篡改,还应通过可信渠道单独核对原始哈希。Get-FileHash 用法

本例验证范围

整理时用随机二进制内容拆成 14 个分片后成功还原,并验证了:已有输出不被覆盖、分片同长度篡改会触发校验失败、空文件可以还原。它只处理文件字节,不保留 NTFS 权限、备用数据流和原始文件时间,也不表示备份文件已经完成数据库恢复验证。


整理自个人 ChatGPT 学习记录,已按主题编辑并核对示例。

— 记录于此,下次继续。