PowerShell压缩文件时忽略错误并归档错误文件的问题求助
解决PowerShell压缩长路径文件时中断的问题
问题根源
原代码使用[io.compression.zipfile]::CreateFromDirectory一次性压缩整个目录,遇到长路径错误时会抛出终止错误,直接中断整个压缩流程,无法继续处理其他正常文件。
修正方案
改用逐个文件遍历的方式处理,跳过报错文件并记录错误信息,最后将错误日志加入压缩包:
# 初始化核心路径变量 $sourceDir = 'C:\Windows\Temp\XYZ\directoryToZip' $zipPath = 'C:\zippedXYZ.zip' $errorLogPath = 'C:\Windows\Temp\XYZ\Error.txt' # 重置错误日志文件 if (Test-Path $errorLogPath) { Clear-Content $errorLogPath } else { New-Item $errorLogPath -ItemType File | Out-Null } # 加载压缩所需程序集 Add-Type -AssemblyName System.IO.Compression.FileSystem # 创建或打开目标压缩包 $zipArchive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create) try { # 遍历目录下所有文件(含子目录) Get-ChildItem -Path $sourceDir -Recurse -File | ForEach-Object { try { # 生成文件在压缩包内的相对路径 $relativePath = $_.FullName.Substring($sourceDir.Length + 1) # 将单个文件添加到压缩包 [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipArchive, $_.FullName, $relativePath) } catch { # 记录错误详情到日志(含时间戳、文件路径、错误信息) "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - 压缩失败: $($_.FullName),错误原因: $($_.Exception.Message)" | Out-File -Append -FilePath $errorLogPath } } } finally { # 确保压缩包资源被正确释放 $zipArchive.Dispose() } # 将错误日志更新到压缩包中 Compress-Archive -Update -Path $errorLogPath -DestinationPath $zipPath
方案说明
- 逐个处理文件,单个文件报错不会中断整体压缩流程,保证正常文件能被成功压缩
- 错误日志包含时间戳、具体文件路径和错误详情,便于后续排查问题
- 最后将错误日志加入压缩包,确保错误记录随压缩包同步交付
- 若需要追加到已有压缩包,可将
ZipArchiveMode::Create改为ZipArchiveMode::Update,建议提前清理旧压缩包避免冗余内容
内容的提问来源于stack exchange,提问作者Kirito
相关产品推荐
相关产品推荐

