繁体   English   中英

powershell 压缩存档 OutOfMemoryException

[英]powershell Compress-Archive OutOfMemoryException

我需要用 power shell 压缩一个文件夹。

有我的代码:

Get-ChildItem $YourDirToCompress -Directory  | 
           where { $_.Name -notin $DirToExclude} | 
              Compress-Archive -DestinationPath $ZipFileResult -Update

Move-Item -Path $ZipFileResult -Destination $ZipFileDest

我得到:

Exception calling "Write" with "3" argument(s): "Exception of type 'System.OutOfMemoryException' was thrown."
At 
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:820 
char:29
+ ...                     $destStream.Write($buffer, 0, $numberOfBytesRead)
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OutOfMemoryException

我已经设定:

Set-Item WSMan:\localhost\Plugin\Microsoft.PowerShell\Quotas\MaxMemoryPerShellMB 8000
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 8000
Restart-Service WinRM

整个文件约为 1.9 GiB,压缩文件为 500 MiB。 我很难相信这真的是内存问题。

此外,它有一次或两次成功创建文件(当 MaxMemoryPerShellMB 设置为 4000 时)。 但大多数时候它失败了。

我能做什么?

我在 2022 年遇到了完全相同的错误:。

Exception calling "Write" with "3" argument(s): "Exception of type
'System.OutOfMemoryException' was thrown."
At C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Arch
ive\Microsoft.PowerShell.Archive.psm1:820 char:29
+ ...                     $destStream.Write($buffer, 0, $numberOfBytesRead)
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OutOfMemoryException

OutOfMemoryException Microsoft.PowerShell.Archive.psm1

经过一番思考,我能够非常简单地解决它。

我也怀疑这真的是内存问题,因为我有 16 GiB 的 RAM,而且它显示只有大约 9 GiB 正在使用。

Microsoft 脚本专家 Ed Wilson 撰写了一篇文章学习如何配置 PowerShell 内存,这可能会为某些人提供解决方案。 在此处输入图像描述 就我而言,它没有,因为 PS 似乎已经配置为使用最大可用内存。

我在通常每隔几天压缩一次的文件夹上遇到问题。 这个文件夹超过 11 GiB,压缩到大约 4 GiB。 这以前已经工作了多年。

但是,考虑一下,要创建这种大小的 zip,我认为 PS 可能会在内存中保存大量数据,直到最后将其提交到文件系统为止。 我意识到虽然这台计算机有 16 GiB 的 RAM 并且显示只有大约 9 GiB 正在使用,但 9 GiB 是该计算机上使用的异常大的内存量。 减去 Windows、图形等使用的内存仍然留下了几个 GiB 的空闲空间——但可能不足以让 PS 创建一个大的 zip 文件。

果然,在重新启动以释放已使用的异常大量 RAM 后,该过程成功运行并像往常一样创建了我的 zipfile。

总之:

  • 检查是否可以配置 PS 使用更多 RAM;
  • 检查任务管理器以查看您的可用 RAM 是否比平时少;
  • 重新启动以使 PS 可用的最大 RAM。

在此处输入图像描述

在此处输入图像描述

似乎 PowerShell 的内置 Zip 模块非常有限,专为简单直接的任务而设计。 这些限制之一是最大文件大小为 2GB。 另外,它获取内存的方式似乎不是很有效。 例如,如果您尝试使用 Windows UI 通过 Winzip 或 WinRar 压缩文件,它可能会起作用。 有关底层库的更多信息https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchive

因此,我建议使用7Zip4Powershell库,它对我来说非常适合相同的文件/Windows 内存等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM