【问题标题】:Issue Loading Assembly in PowerShell with AssemblyConfigurationEntry使用 AssemblyConfigurationEntry 在 PowerShell 中加载程序集问题
【发布时间】:2012-09-13 14:01:50
【问题描述】:

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

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    您可以从脚本中调用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

    【讨论】:

    • 我在其他计算机上尝试了我的代码,它工作得很好。你的也是一个很好的解决方法。感谢您的提示。
    猜你喜欢
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    相关资源
    最近更新 更多