Add-Type: 无法添加类型。找不到程序集'System.IO.Compression.FileSystem'。

9

我在TeamCity Builds中使用简单的PowerShell脚本。

它需要System.IO.Compression.FileSystem,并且代理服务器已安装.NET 4.5.2。以下是安装的.NET框架版本:

PSChildName         Version             Release             Product            
-----------         -------             -------             -------            
v2.0.50727          2.0.50727.5420                                             
v3.0                3.0.30729.5420                                             
Windows Communic... 3.0.4506.5420                                              
Windows Presenta... 3.0.6920.5011                                              
v3.5                3.5.30729.5420                                             
Client              4.5.51209           379893              4.5.2              
Full                4.5.51209           379893              4.5.2              
Client              4.0.0.0                                    

这个 PowerShell 脚本中有以下代码行:
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
Add-Type -AssemblyName System.IO.Compression.FileSystem

在第二行执行时出现错误

Add-Type : Cannot add type. The assembly 'System.IO.Compression.FileSystem' could not be found.
At C:\BuildAgent\someFile.ps1:104 char:13
+     Add-Type <<<<  -AssemblyName System.IO.Compression.FileSystem
+ CategoryInfo          : ObjectNotFound: (System.IO.Compression.FileSystem:String) [Add-Type], Exception
+ FullyQualifiedErrorId : ASSEMBLY_NOT_FOUND,Microsoft.PowerShell.Commands.AddTypeCommand

奇怪的是,我预计在使用.NET 4.5.2时,PowerShell应该能够从GAC中加载程序集。任何帮助将不胜感激。

1
你使用的是哪个PowerShell版本?更重要的是,该PowerShell使用哪个.NET版本?也许你需要强制它使用.NET 4才能成功加载这个库。 - ForNeVeR
我正在使用.NET版本v4.0.30319覆盖powershell.exe.config。它显示System.IO.Compression.FileSystem的GAC=true,但无法加载相同的程序集。 - GeekzSG
4个回答

7
尝试加载特定的DLL文件:
Add-Type -Path C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IO.Compression.FileSystem\v4.0_4.0.0.0__b77a5c561934e089\System.IO.Compression.FileSystem.dll

太棒了!你能在这里帮忙吗?http://stackoverflow.com/questions/39801315/how-to-chain-commands-at-a-special-powershell-4-command-prompt - johny why

1

LoadWithPartialName()已被弃用,因此尽可能避免使用它;但是,如果LoadWithPartialName()在您的上下文中已经起作用,您也可以使用返回的对象的Location属性来加载DLL。

if($PSVersionTable.PSVersion -lt '5.0'){
   Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")).Location;
}else{
   Add-Type -AssemblyName System.IO.Compression.FileSystem
}

LoadWithPartialName已经被弃用,你不应该使用它,因为以后会遇到麻烦。 - JrBriones
@JrBriones 还有这个 https://dev59.com/am025IYBdhLWcg3wQDhb#6131116 - Gregor y
@JrBriones,这是PowerShell的旧版本,否则请使用Add-Type -As System.IO.Compression.FileSystem - Gregor y
@JrBriones,尽可能避免更新。 - Gregor y

0
尝试改为以下代码(并删除最后一部分) Add-Type -AssemblyName System.IO.Compression

0
当我运行PowerShell脚本时,遇到了完全相同的错误。我猜测这是安装的.Net版本与PowerShell版本之间的某种冲突。在我的情况下,只需将PowerShell版本更新到最新版本即可解决问题。可以在此处找到最新版本:

https://www.microsoft.com/en-us/download/details.aspx?id=40855


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接