Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference .NET assemblies using PowerShell

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?

like image 908
Russell Avatar asked Jun 20 '10 13:06

Russell


People also ask

What is reflection assembly in PowerShell?

Reflection. Assembly class. This means that you can pass it to the Get-Member Windows PowerShell cmdlet and see what methods, properties and events are available.

What are assemblies PowerShell?

An assembly is a packaged chunk of functionality (the . NET equivalent of a DLL). Almost universally an assembly will consist of exactly one file (either a DLL or an EXE).


2 Answers

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) 
like image 183
Andy Schneider Avatar answered Sep 18 '22 19:09

Andy Schneider


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) 
like image 34
Darin Dimitrov Avatar answered Sep 21 '22 19:09

Darin Dimitrov