PowerShell Cookbook

Twitter Updates

    follow me on Twitter

    Search

    Categories

     

    On this page

    Load a Custom DLL from PowerShell

    Archive

    Blogroll

    Disclaimer
    I work for Microsoft.

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    RSS 2.0 | Atom 1.0 | CDF

    Send mail to the author(s) E-mail

    Total Posts: 235
    This Year: 12
    This Month: 0
    This Week: 0
    Comments: 634

    Sign In

     Friday, October 27, 2006
    Friday, October 27, 2006 8:20:50 PM (Pacific Daylight Time, UTC-07:00) ( )

    One of the amazing features of PowerShell is its amazing reach.  You can interact with the file system, the registry, certificate stores, COM, WMI, XML, cmdlets, providers … the list seems to go on forever.

    One important extension point is the ability to seamlessly interact with .NET DLLs. These are most commonly shipped in SDKs, and many people have made use of this.  For example:

    When pre-built API DLLs don't suit your need, you have yet another option -- writing your own! If you are comfortable with any of the .NET languages, it is quite simple to compile a DLL and load it into your PowerShell session.

    Take, for example, a simple math library.  It has a static Sum method, and an instance Product method:

    namespace MyMathLib
    {
      public class Methods
      {
        public Methods()
        {
        }

        public static int Sum(int a, int b)
        {
          return a + b;
        }

        public int Product(int a, int b)
        {
          return a * b;
        }
      }
    }

    Here is everything required to get that working in your PowerShell system:

    [C:\temp]

    PS:25 > notepad MyMathLib.cs

     

    (…)

     

    [C:\temp]

    PS:26 > csc /target:library MyMathLib.cs

    Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42

    for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727

    Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

     

     

    [C:\temp]

    PS:27 > [Reflection.Assembly]::LoadFile("c:\temp\MyMathLib.dll")

     

    GAC    Version        Location

    ---    -------        --------

    False  v2.0.50727     c:\temp\MyMathLib.dll

     

     

     

    [C:\temp]

    PS:28 > [MyMathLib.Methods]::Sum(10, 2)

    12

     

    [C:\temp]

    PS:29 > $mathInstance = new-object MyMathLib.Methods

    Suggestion: An alias for New-Object is new

     

    [C:\temp]

    PS:30 > $mathInstance.Product(10, 2)

    20

    Comments [8] | | #