Joshua Dale
Joshua Dale

Reputation: 1793

Issue Loading Assembly in PowerShell with AssemblyConfigurationEntry

I am running into issues loading an assembly into a PowerShell Runspace within a .net console application.

When running the application, I get the following error: "Cannot find type [Test.Libary.TestClass]: make sure the assembly containing this type is loaded."

I tried installing the assembly into the GAC, but it didn't seem to make any difference. I couldn't seem to find very much documentation on the AssemblyConfigurationEntry class, so any help is appreciated.

Console Application:

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; }
    }
}

Upvotes: 2

Views: 1821

Answers (1)

latkin
latkin

Reputation: 16792

You can call Add-Type from script to accomplish this.

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();

This should work if your DLL is in the GAC. Otherwise, when calling Add-Type instead of -AssemblyName Test.Library, you would instead need to use -Path c:\path\to\Test.Library.dll

Upvotes: 2

Related Questions