2012-09-13 29 views
2

我遇到一個.NET控制檯應用程序中加載裝配成一個PowerShell運行空間問題。問題裝載組件在PowerShell和AssemblyConfigurationEntry

運行應用程序時,我得到了以下錯誤:「找不到類型[Test.Libary.TestClass]:要確保在加載包含此類型的程序集」

我嘗試安裝裝配到GAC,但它似乎沒有任何區別。我似乎無法找到關於AssemblyConfigurationEntry類的很多文檔,所以我們不勝感激。

控制檯應用程序:

namespace PowerShellHost 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string assemblyPath = Path.GetFullPath("Test.Library.dll"); 

      RunspaceConfiguration config = RunspaceConfiguration.Create(); 

      var libraryAssembly = new AssemblyConfigurationEntry("Test.Library, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d7ac3058027aaf63", assemblyPath); 
     config.Assemblies.Append(libraryAssembly); 

      Runspace runspace = RunspaceFactory.CreateRunspace(config); 
      runspace.Open(); 

      PowerShell shell = PowerShell.Create(); 
      shell.Runspace = runspace; 

      shell.AddCommand("New-Object"); 
      shell.AddParameter("TypeName", "Test.Libary.TestClass"); 

      ICollection<PSObject> output = shell.Invoke(); 
     } 
    } 
} 

Test.Library.dll:

namespace Test.Library 
{ 
    public class TestClass 
    { 
     public string TestProperty { get; set; } 
    } 
} 

回答

2

您可以撥打Add-Type從腳本來做到這一點。

PowerShell shell = PowerShell.Create(); 

shell.AddScript(@" 
Add-Type -AssemblyName Test.Library 

$myObj = New-Object Test.Library.TestClass 
$myObj.TestProperty = 'foo' 
$myObj.TestPropery 
"); 

ICollection<PSObject> output = shell.Invoke(); 

如果您的DLL位於GAC中,這應該有效。否則,在撥打Add-Type而不是-AssemblyName Test.Library時,您需要使用-Path c:\path\to\Test.Library.dll

+0

我在其他計算機上試過我的代碼,它工作得很好。你也是一個很好的解決方法。謝謝你的提示。 –