2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried my code on other computers and it worked just fine. Your is also a good workaround. Thanks for the tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.