You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Compress-Archive压缩550MB bak文件报OutOfMemoryException错误

问题原因
  • 该报错并非因为压缩文件超出2GB限制,本质是PowerShell自带Compress-Archive cmdlet的内存管理缺陷:该命令执行时会将大量待压缩内容一次性加载到内存缓冲区,当系统可用内存不足,或你使用的是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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:06:00