Can't get powershell script to run inside PowerGUI
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 d开发者_开发技巧o I need to do to get the script to run in PowerGUI? Ideally, I'd like the DLLs in a different directory than $PSHOME.
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.
Use set-psdebug -trace 2 to see what it is attempting to call exactly.
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.
精彩评论