Wednesday, July 23, 2008

Create Assembly and Import into PowerShell

I don't see much documentation on how to create and import your own assembly (DLL) file into PoSH so I thought I would shed some light into how I've done this. So why would you do this anyway? Well if you've created your own custom .Net Class or you want to create an assembly file from code somebody has shared and import that into PowerShell to use.

I'm not a developer so feel free to correct me if I state some untruths here. My examples are with Visual Studio 2005.

First, create your assembly (DLL) file. This is just a Fibonacci C# series example that I've seen on the web. Note: the class and methods if you wish to use them in PS must be public!


   1:  using System;
   2:  
   3:  public class Fib
   4:  {
   5:      Decimal current;
   6:      Decimal last;
   7:      public Fib()
   8:      {
   9:          current = 1;
  10:          last = 0;
  11:      }
  12:      private Fib(Decimal last, Decimal secondToLast)
  13:      {
  14:          current = last + secondToLast;
  15:          this.last = last;
  16:      }
  17:      public Fib GetNext()
  18:      {
  19:          return new Fib(current, last);
  20:      }
  21:      public Decimal Value
  22:      {
  23:          get { return current; }
  24:      }
  25:  }

Build the Assembly.



This will create your DLL file, for me it was located in my ~\Visual Studio 2005\Projects\pstest\pstest\bin\Release folder
Although not needed, I moved the file to my desktop to I can reach it faster.

After the assembly has been created your ready to import it into PS. With V.1 of PS you need to use reflection to import the assembly. In v2 you can use the new cmdlet Add-Type. I don't have V2 so I'll list the reflection method. Remember when importing the assembly you must use the entire path, relative paths will throw an error.

_=\|/=_PoSH_=\|/=_ $assemblyFile = Join-Path $home "\desktop\pstest.dll"
_=\|/=_PoSH_=\|/=_ [System.Reflection.Assembly]::LoadFile($assemblyFile)

GAC Version Location
--- ------- --------
False v2.0.50727 C:\Users\jdelatorre\Desktop\pstest.dll


_=\|/=_PoSH_=\|/=_ $fib = New-Object fib
_=\|/=_PoSH_=\|/=_ for ($i = 0;$i -lt 10;$i++) {
>> $fib = $fib.GetNext()
>> $fib.Value
>> }
>>
1
2
3
5
8
13
21
34
55
89
_=\|/=_PoSH_=\|/=_

As you can see I create the object FIB using the New-Object Cmdlet. Then I loop through the Fibonacci numbers using a "for" loop showing the use of the Class's public methods and properties.

No comments: