How can I get PowerShell Added-Types to use Added Types


I’m working on a PoSh project that generates CSharp code, and then Add-Types it into memory.

The new types use existing types in an on disk DLL, which is loaded via Add-Type.

All is well and good untill I actualy try to invoke methods on the new types. Here’s an example of what I’m doing:

Running the above script gives the following error on the last line:

Exception calling “CallTestClassOne” with “0” argument(s):
“Could not load file or assembly ‘TestClassOne,…’
or one of its dependencies. The system cannot find the file specified.”
At AddTypeTest.ps1:39 char:20
+ $b.CallTestClassOne <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

What am I doing wrong?


This happens because any assemblies are looked for by the CLR loader in the application’s (PowerShell’s) base directory. Of course, it doesn’t find your assembly there. The best way to solve this is to hook the AssemblyResolve event as stej mentions but use it to tell the CLR where the assembly is. You can’t do this with PowerShell 2.0’s Register-ObjectEvent because it doesn’t work with events that require a return value (ie the assembly). In this case, let’s use more C# via Add-Type to do this work for us. This snippet of code works:


How can I get PowerShell Added-Types to use Added Types by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply