Unable to find type [System.IO.Compression.CompressionLevel]: make sure that the assembly containing this type is loaded
Solution 1
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.
Solution 2
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.
Solution 3
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.
Maven
Updated on October 10, 2020Comments
-
Maven over 3 years
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.0How can I make this work?