PowerShell调用Compress-Archive压缩550MB bak文件报OutOfMemoryException错误
问题原因
- 该报错并非因为压缩文件超出2GB限制,本质是PowerShell自带
Compress-Archivecmdlet的内存管理缺陷:该命令执行时会将大量待压缩内容一次性加载到内存缓冲区,当系统可用内存不足,或你使用的是32位版本PowerShell时(32位进程默认最大可用内存不到1GB,扣除基础开销后很容易无法支撑550MB文件的最优压缩计算),就会触发OutOfMemory异常。
解决方案
1. 优先更换执行环境
确认你使用的是64位版本的PowerShell:打开任务管理器查看PowerShell进程,若后缀标注*32,请更换路径为C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe的64位程序执行脚本,解除32位进程的内存上限限制。
2. 替换为.NET原生压缩实现(兼容性最好)
将脚本中Compress-Archive相关代码替换为.NET底层的ZipFile类实现,内存占用远低于PowerShell自带cmdlet,修改后的压缩逻辑如下:
# 原Compress-Archive代码替换为以下内容 Add-Type -AssemblyName System.IO.Compression.FileSystem $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal $zipArchive = [System.IO.Compression.ZipFile]::Open($pathzip, [System.IO.Compression.ZipArchiveMode]::Create) [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipArchive, $path, (Split-Path $path -Leaf), $compressionLevel) $zipArchive.Dispose()
3. 调用系统自带tar命令(性能最优)
Windows 10 1809及以上、Windows 11系统均原生自带tar命令,完全没有内存溢出问题,压缩速度更快,代码更简洁:
# 原Compress-Archive代码替换为以下内容 tar -a -c -f $pathzip $path
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

