System.IO.Compression问题

时间:2017-08-08 06:26:17

标签: powershell zip

我有一个带有.Net 4.5的PowerShell v2脚本,它压缩旧文件。像这样:

[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
...
$files = Get-Childitem ...
...
$zip = [System.IO.Compression.ZipFile]::Open($arcpath + $curname, "Create")
foreach ($onefile in $files) {
  [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $onefile.FullName, $onefile.Name, "Optimal") | out-null
}

在我安装.Net 4.6.1(其他项目需要)之前,它工作正常。

现在它抛出一个错误:

The following exception occurred while retrieving member "Open": "Could not load
file or assembly 'System.IO.Compression, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies.
Reference assemblies should not be loaded for execution.  They can only be loaded
in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)"
At line:1 char:7
+ $zip = <<<<  [System.IO.Compression.ZipFile]::Open('C:\Temp\1.zip', "Create")
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember

我安装了WMF 5.1以使用本机ps5压缩功能。但它也会引发错误:

Compress-Archive -Path $files -DestinationPath C:\Temp\Script\test.zip -CompressionLevel Optimal
Add-Type : Could not load file or assembly 'System.IO.Compression, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies.
Reference assemblies should not be loaded for execution.  They can only be loaded
in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:469 char:9
+         Add-Type -AssemblyName System.IO.Compression
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], BadImageFormatException
    + FullyQualifiedErrorId : System.BadImageFormatException,Microsoft.PowerShell.Commands.AddTypeCommand

我该如何解决?

2 个答案:

答案 0 :(得分:0)

卸载NET 4.6.1,安装NET 4.6.2。问题已得到解决。

答案 1 :(得分:0)

最后发现了这个问题。我们使用使用NLog的自定义解决方案。 NLog将System.IO.Compression的引用添加到解决方案中。在安装解决方案期间,它部署了dll(可能是旧的或以某种不正确的方式)。我们从安装程序中排除了dll,现在一切正常。