Unable to find type [System.IO.Compression.CompressionLevel]: make sure that the assembly containing this type is loaded

Maven picture Maven · Jun 5, 2014 · Viewed 55.1k times · Source

I wrote this PowerShell script to archive all log files created during a certain date range.

$currentDate = Get-Date;
$currentDate | Get-Member -Membertype Method Add;
$daysBefore = -1;
$archiveTillDate = $currentDate.AddDays($daysBefore);

$sourcePath = 'C:\LOGS';
$destPath='C:\LogArchieve\_'+$archiveTillDate.Day+$archiveTillDate.Month+$archiveTillDate.Year+'.zip';

foreach( $item in (Get-ChildItem $sourcePath | Where-Object { $_.CreationTime -le $archiveTillDate }) )
{
    [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal;
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcePath,$destPath, $compressionLevel, $false);
}

It works until the foreach loop, but once in the loop it gives these errors:

Unable to find type [System.IO.Compression.CompressionLevel]: make sure that the assembly containing this type is loaded.
At line:4 char:65
+ $compressionLevel = [System.IO.Compression.CompressionLevel] <<<< ::Optimal;
+ CategoryInfo          : InvalidOperation: (System.IO.Compression.CompressionLevel:String) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

As System.IO.Compression is part of .NET 4.5, I have it installed on the system, but I still get these errors. I am on Windows Server 2008 R2 and using PowerShell v2.0

How can I make this work?

Answer

bincob picture bincob · Sep 2, 2016

Try using Add-Type -AssemblyName System.IO.Compression.FileSystem instead. It is cleaner and does not have a dependency on the reference assemblies which need an installation of Visual Studio.