使用 Add-Type 加载 System.IO.Compression.FileSystem 抛出错误

Load System.IO.Compression.FileSystem with Add-Type throws error

我想使用 PowerShell 提取一个 zip 文件。所以,我用这个:

Add-Type -AssemblyName System.IO.Compression.FileSystem

# some code to download the zip file from FTP #

[System.IO.Compression.ZipFile]::ExtractToDirectory($localpath+"\Test.zip",$localpath)

我收到错误消息:添加类型:无法添加类型。找不到程序集 'System.IO.Compression.FileSystem'。

然后我搜索了 Whosebug 并更改了

Add-Type -AssemblyName System.IO.Compression.FileSystem

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

它说:

Error: Could not load file or assembly 'file:///C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFram
ework\v4.6.1\System.IO.Compression.FileSystem.dll' or one of its dependencies. This assembly is built by a runtime newer
 than the currently loaded runtime and cannot be loaded.

我实际上可以在那个 v4.6.1 路径中看到这个 dll。它在那里。请问我的语法有什么问题吗?

你的语法没有问题;问题是该程序集与您的 PowerShell 版本不兼容 - 这正是第二个错误所说的。对于第一个错误,PowerShell 可能根本没有将该路径作为其搜索程序集 DLL 的路径的一部分,因为它们不兼容(同样,请参阅第二次尝试的错误,您在其中为程序集指定了正确的路径) .

如果可以,您不妨考虑updating your PowerShell (and Windows Management Framework)。当前的 PowerShell 版本是 5.

如果您使用的是 Powershell 版本 5+,则可以使用 Expand-Archive 来解压缩文件。看到这个 msdn link.

我在使用 Compress-Archive 时遇到了类似的问题,它在 Win10 上有效,但在 Win Srv 2012 R2 上无效,甚至认为语法正确并且 DLL 存在于上述路径中。

然后我注意到 PowerShell 在 Win10 上的版本是 5,在 WinSrv 上是 4,所以我安装了 Windows 管理框架 (WMF) 5.1,其中包括并更新到 PS 然后当WinSrvR2 上 PS 的版本也是 5,此命令随后起作用。