63

I am a C# .NET developer/architect and understand that it uses objects (.NET objects) and not just streams/text.

I would like to be able to use PowerShell to call methods on my .NET (C# library) assembies.

How do I reference an assembly in PowerShell and use the assembly?

2 Answers 2

71

With PowerShell 2.0, you can use the built in Cmdlet Add-Type.

You would just need to specify the path to the dll.

Add-Type -Path foo.dll

Also, you can use inline C# or VB.NET with Add-Type. The @" syntax is a HERE string.

C:\PS>$source = @"
    public class BasicTest
    {
        public static int Add(int a, int b)
        {
            return (a + b);
        }

        public int Multiply(int a, int b)
        {
            return (a * b);
        }
    }
    "@

    C:\PS> Add-Type -TypeDefinition $source

    C:\PS> [BasicTest]::Add(4, 3)

    C:\PS> $basicTestObject = New-Object BasicTest 
    C:\PS> $basicTestObject.Multiply(5, 2)
Sign up to request clarification or add additional context in comments.

6 Comments

A couple options for that PowerShell in Visual Studio: powerguivsx.codeplex.com PowerShell Plus: IDE powershellplus.com
The latest ISE has intellisense.
Add-Type : Cannot add type. The ".EXE" extension is not supported.
just press tab for autocomplete, and get used to doing |gm a ton. no need for an IDE.
I worked around 'The ".EXE" extension is not supported' by renaming it to .DLL :P
|
63

Take a look at the blog post Load a Custom DLL from PowerShell:

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;
        }
    }
}

Compile and run in PowerShell:

> [Reflection.Assembly]::LoadFile("c:\temp\MyMathLib.dll")
> [MyMathLib.Methods]::Sum(10, 2)

> $mathInstance = new-object MyMathLib.Methods
> $mathInstance.Product(10, 2)

13 Comments

The link is loading here. I will update my post and copy the relevant part from the it.
Thanks for the text. :) I know now why I couldn't find the answer when I was searching. I'll try it and let you know how I go. :)
@Russell: add-type -path .\foo.dll. You can also use it to directly compile code.
@Johannes, Darin is basically right. His solution will work. However, if somebody else will come here (e.g. from google), he will see his answer and will not read through the comments. That's why I think there should be another answer with Add-Type.
404 on the link at the start of your post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.