Question:
In my power shell script I am loading a custom assembly and then instantiating a class of that assembly by New-Object
.
Assembly.LoadFile()
executes successfully but New-Object
statement gives the bellow exception.
1 2 3 |
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of i ts dependencies. The system cannot find the file specified." |
Script:
1 2 3 |
[System.Reflection.Assembly]::LoadFile("MyAssembly.dll") $a=New-Object MyAssembly.MyClass -ArgumentList "arg1" |
This custom assembly references only the following assemblies
1 2 3 4 5 6 7 |
System System.Core System.Runtime.Serialization System.Xml.Linq System.Data System.Xml |
I tried explicitly loading the System.Runtime.Serialization dll like below. But same exception
1 2 |
[System.Reflection.Assembly]::Load("System.Runtime.Serialization, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") |
Any idea?
Answer:
Don’t use LoadFile
. Since you are using Powershell V2, the preferred method is Add-Type
1 2 |
Add-Type -AssemblyName "MyLibrary.dll" |
http://www.dougfinke.com/blog/index.php/2010/08/29/how-to-load-net-assemblies-in-a-powershell-session/ has a good list of the different ways available to import a library into the current shell runspace.
http://technet.microsoft.com/en-us/library/hh849914.aspx is the technet documentaion on Add-Type and has examples including how to use static methods in a loaded library