c# - 使用 AssemblyConfigurationEntry 在 PowerShell 中加载程序集时出现问题

标签 c# powershell

我在将程序集加载到 .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/

相关文章:

c# - 您会使用什么语言在内存棒上实现自动更新/同步功能?

c# - WPF 拼写检查在内部是如何工作的?

c# - 如何将公共(public) Web 服务 API 设为私有(private)?

powershell - Powershell DirectoryService对象错误既未捕获也未捕获

powershell - 如何使用 Get-ChildItem 获取特定文件

powershell - 如何使用powershell小写除第一个字符之外的字符串

c# - 从另一个用户应用程序在 Facebook 业务页面上发布

c# - 引用类型还需要通过 ref 传递吗?

powershell - 相当于 Powershell 中的 'more' 或 'less' 命令?

xml - 使用PowerShell,如何使用多个命名空间