powershell 2 new-object "Cannot find type..." exception when instantiate .net class implemented interface from external library powershell 2 new-object "Cannot find type..." exception when instantiate .net class implemented interface from external library powershell powershell

powershell 2 new-object "Cannot find type..." exception when instantiate .net class implemented interface from external library


Instead of ::LoadFile, use:

[System.Reflection.Assembly]::LoadFrom(‘c:\LibraryA.dll’)[System.Reflection.Assembly]::LoadFrom(‘c:\LibraryB.dll’)

When you use ::LoadFrom the assembly will be loaded into a context with the directory it was loaded from, referenced assemblies in that same directory will automatically be resolved. ::LoadFile is meant for loading assemblies that share an identity but are in different directories and does not keep any load context, so referenced assemblies are not resolved.


The answer to this question solves your issue:How can I get PowerShell Added-Types to use Added Types

The key is to use the AppDomain.CurrentDomain.AssemblyResolve event.

You can, for example, add the AssemblyResolver class (from the post above) to your LibraryA and then use [Utils.AssemblyResolver]::AddAssemblyLocation("LibraryB.dll") to pull in the LibraryB reference when needed.

Or, just to prove the point:

[System.AppDomain]::CurrentDomain.add_assemblyResolve({    If ($args[1].Name.StartsWith("LibraryB"))    {        Return [System.Reflection.Assembly]::LoadFile("C:\LibraryB.dll")    }    Else    {        Return $Null    }})

Note that you have a circular dependency in your example above: LibraryA is referencing LibraryB and LibraryB references LibraryA. You will probably want to fix that first - assuming you have the same in your real project...