views:

280

answers:

4

When I run my script directly from the Powershell console it works. When I run my script in PowerGUI and try instantiate an object, I get an error:

Exception calling ".ctor" with "3" argument(s): "Could not load file or assembly 'MyLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=77f676cc8f85d94e' or one of its dependencies. The system cannot find the file specified."

If I put all of the needed DLLs in $PSHOME, the script will successfully run from the console but not PowerGUI. If I move the DLLs to a local directory and load the DLLs with reflection, the script will not run in PowerGUI nor the powershell console.

[reflection.assembly]::loadfile('c:\mylibs\mylib.dll')

What do I need to do to get the script to run in PowerGUI? Ideally, I'd like the DLLs in a different directory than $PSHOME.

A: 

I changed loadfile to loadfrom but that didn't make a difference.

gerald
I just noticed this after I posted the excerpt from LoadFile. Keep in mind you *will* need to close and restart PowerGUI or the PowerShell console after you change to LoadFrom because your assembly has already been loaded in the LoadFile context and CLR won't try to load it again.
Josh Einstein
Yep. PowerGUI crashed. After restarting it worked. Thanks for the help.
gerald
A: 

Use set-psdebug -trace 2 to see what it is attempting to call exactly.

rerun
A: 

This could be because PowerGUI is a different PowerShell host so its 'local folder' is PowerGUI's folder in Program Files, and not $pshome - where you put the DLLs.

DSotnikov
+2  A: 

You should be using [Assembly]::LoadFrom as opposed to LoadFile. LoadFile is intended for loading assemblies that cannot be loaded in the normal assembly loading context such as the case where you are trying to load two versions of the same assembly. It does not use the normal probing rules so that is why it doesn't automatically load dependencies. Here's an excerpt from the documentation for LoadFile.

Use the LoadFile method to load and examine assemblies that have the same identity, but are located in different paths. LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does. LoadFile is useful in this limited scenario because LoadFrom cannot be used to load assemblies that have the same identities but different paths; it will load only the first such assembly.

If you are using PowerShell 2.0 you may wish to use Add-Type instead:

Add-Type -Path c:\mylibs\mylib.dll

And if all else fails, run Fuslogvw.exe to find out why binding fails.

Josh Einstein