我在将程序集加载到 .net 控制台应用程序内的 PowerShell 运行空间时遇到问题。
运行应用程序时,出现以下错误:“找不到类型 [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; }
}
}
最佳答案
您可以从脚本中调用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
关于c# - 使用 AssemblyConfigurationEntry 在 PowerShell 中加载程序集时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399703/