Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 855
Maven Avatar asked Jun 05 '14 11:06

Maven


3 Answers

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.

like image 115
bincob Avatar answered Nov 09 '22 03:11

bincob


You can manually add a .NET class to your PowerShell session.

Remove [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem"); from your script and add the following at the very top:

Add-Type -Path "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll"

Or on a 32-bit box:

Add-Type -Path "C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll"

This presumes .NET 4.5 installed OK on your system and System.IO.Compression.FileSystem.dll actually exists.

like image 18
Raf Avatar answered Nov 09 '22 02:11

Raf


Also, make sure to check your $pshome exe.config file. I had an issue once where Powershell ISE refused to load a .NET assembly, because the config file had .NET 2.0 listed instead of 4.

like image 1
user7413048 Avatar answered Nov 09 '22 03:11

user7413048