来自cs的Add-Type,需要引用程序集

时间:2011-11-24 08:42:33

标签: powershell powershell-v2.0

我使用非常简单的代码提供了一个cs文件:

using Ionic.Zip;
public static class Helper
{
        public static ZipFile GetNewFile(string fileName)
        {       
            return new ZipFile(fileName);
        }
}

它需要Ionic.Zip组装。我想将这种类型添加到我的powershell中:

cd c:\pst
Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll"
$var = [Helper]::GetNewFile("aaa")

当我这样做时它给了我:

The following exception occurred while retrieving member "GetNewFile": "Could not load file or assembly 'Ionic.Zip, Version=1.9.1.8, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c' or one of its dependencies. The located assembly'
s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

它似乎已在某个临时位置编译了程序集,但在那里找不到Ionic.Zip。

但是,如果指定输出程序集然后添加此程序集,则可以正常工作:

cd c:\pst
Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll" -OutputAssembly "T.dll"
Add-Type -Path "T.dll"

$var = [Helper]::GetNewFile("aaa")
$var.AlternateEncoding

所以我想知道是否有办法避免使用输出汇编?

2 个答案:

答案 0 :(得分:6)

在Powershell v3 CTP1中,您可以解析zip库的完整路径(fullname)并引用:

$ziplib = (get-item ionic.zip.dll).fullname
[void][reflection.assembly]::LoadFrom($ziplib)
Add-Type -Path "2.cs" -ReferencedAssemblies $ziplib
$var = [Helper]::GetNewFile("aaa")
$var.AlternateEncoding

答案 1 :(得分:1)

你必须把你的ionic.zip.dll文件in the GAC 然后在powershell上你可以这样做:

C:\ps> [System.Reflection.Assembly]::LoadWithPartialName("ionic.zip")
C:\ps> Add-Type -Path "2.cs" -ReferencedAssemblies "Ionic.Zip.dll"
C:\ps> $var = [Helper]::GetNewFile("aaa")
C:\ps> $var.name
aaa