powershellsystem.reflection

Why can't PowerShell find .NET libraries from loaded assembly?


I have a .NET assembly that I retrieve from a service that gets put into a byte[]. I then load this assembly using reflection. Despite this being successful, PowerShell will give an error saying it is unable to find the type. Why is this happening? Is it even looking?

[byte[]]$bytes = #Code to get the assembly from the service
$asse = [reflection.assembly]::(“Load”)($bytes); 
[Class1]::("Test")()


 Unable to find type [Class1].
 At line:5 char:1
 + [Class1]::("Test")()
 + ~~~~~~~~
      + CategoryInfo          : InvalidOperation: (Class1:TypeName) [], RuntimeException
      + FullyQualifiedErrorId : TypeNotFound

The .NET class is defined below.

    public class Class1
    {
       public static void Test()
       {  
          System.Diagnostics.Process.Start("calc.exe");
       }
   }

I initially thought it was an issue with the version of Powershell not being in agreement with the .NET version that was used to compile the assembly, however I have confirmed that Powershell is using CLR version 4.0.30319.42000. I have built the .NET assembly with .NET 4.0. Despite this the problem persists.

Also, when I run GetExportedTypes() on $asse, PowerShell has no trouble finding the type.

IsPublic IsSerial Name                                     BaseType                                                      
-------- -------- ----                                     --------                                                      
True     False    Class1                                   System.Object 

I am at a loss of how to move forward on fixing this. Any help would be greatly appreciated.


Solution

  • As hinted in the comments, you need to use at least a namespace-qualified type name, eg.:

    [Namespace.Used.By.Dave.Class1]
    

    To see the full name including the namespace, look at the FullName property on the exported type:

    $asse.GetExportedTypes().Where({$_.Name -eq 'Class1'}) |% FullName