3

Im new to powershell and scripting.

I'm trying to compress IIS Log files (60GB total) using compress-archive cmdlet, however everytime I get the error:

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

I've already adjusted MaxMemoryPerShellMB to 2048MB and restarted the WinRM service.

RAM Memory consumption exceeds 6GB when the command is executed.

Code I'm using follows:

$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

Powershell version is 5. Can anyone guide me on this please?

Thanks in advance.

joebegborg07
  • 869
  • 5
  • 16
  • 24
  • 3
    A [comment on Stackoverflow](https://stackoverflow.com/questions/39898787/compressing-files-with-powershell-throws-outofmemory-exception) suggests to use the [.NET classes](https://blogs.technet.microsoft.com/heyscriptingguy/2015/03/09/use-powershell-to-create-zip-archive-of-folder/). – Daniel Apr 25 '17 at 16:30
  • There is also a [suggestion on uservoice](https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/17349748-compress-archive-throws-outofmemory-on-large-fol) – Daniel Apr 25 '17 at 16:31

1 Answers1

4

As noted by Daniel, use the .NET class. You can do this like so:

# File or directory to zip
$sourcePath = "C:\Path\To\File"
# Resulting .zip file
$destinationPath = "C:\Path\To\File.zip"
# Compression level. Optimal means smallest size, even if it takes a little longer to compress
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
# Whether or not to include root directory (if zipping a directory) in the archive
$includeBaseDirectory = $false
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory("$sourcePath","$destinationPath",$compressionLevel,$includeBaseDirectory)

That'll create a zip of the directory and use little to no RAM. I tried zipping the same (25 GB large) directory with both methods. Using Compress-Archive I was seeing upwards of 6GB RAM usage before I had to kill the host process, whereas using the above showed 0 increase in RAM usage by the powershell host process.

Dusty Vargas
  • 296
  • 1
  • 3
  • 12