"OutOfMemoryException" 对 60Gb 文件使用 Compress-Archive 时

"OutOfMemoryException" when using Compress-Archive with 60Gb of files

我正在尝试使用 Compress-Archive 压缩 IIS 日志文件(总共 60GB),但出现错误:

"Exception of type 'System.OutOfMemoryException' was thrown."

$exclude = Get-ChildItem -Path . | Sort-Object -Descending | Select-Object -First 1
$ArchiveContents = Get-ChildItem -Path . -Exclude $exclude | Sort-Object -Descending
Compress-Archive -Path $ArchiveContents -DestinationPath .\W3SVC2.zip -Force

我已经将 MaxMemoryPerShellMB 调整为 2048MB 并重新启动了 WinRM 服务。

执行命令时RAM内存消耗超过6GB。

按照 Matt 的建议,我建议将其归档到文件集中。类似于:

For($i=0;$i -le $ArchiveContents.Count;$i=$i+10){
    Compress-Archive -Path $ArchiveContents[$i..($i+9)] -DestinationPath .\W3SVC2-$i.zip -Force
}

这样您一次只能处理 10 个文件。您可能需要调整文件的数量,具体取决于您拥有的文件数量和文件的大小,即:如果您有 300 个文件,每个文件大小为 200MB,那么一次 10 个可能比较好,而如果您有 3000 个文件,每个文件大小为 20MB每个你可能想增加到 50 甚至 100。

编辑:我刚看了,Compress-Archive支持通过指定-Update参数添加文件到压缩包。您应该可以做与上面相同的事情,稍微修改一下,制作 1 个大存档。

For($i=0;$i -le $ArchiveContents.Count;$i=$i+10){
    Compress-Archive -Path $ArchiveContents[$i..($i+9)] -DestinationPath .\W3SVC2.zip -Update
}

应该一次只将 10 个文件添加到目标存档,而不是尝试一次添加所有文件。

以下解决方案提供比 Compress-Archive

更好的性能

创建 OptimalCompression。ps1

Create Windows Optimized Compression
ECHO OFF
ECHO Starting Compressing $args[0] to $args[1]
$source = $args[0]
$destination = $args[1]
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includeBaseDirectory = $false
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory("$sourcePath","$destinationPath",$compressionLevel,$includeBaseDirectory)
PAUSE

运行 需要参数的命令

C:\> powershell .\OptimalCompress.ps1 c:\YourSourceFolder c:\YourDestinationFile.zip