Cómo reference.NET ensamblados con PowerShell


Soy un desarrollador/arquitecto de C#. NET y entiendo que usa objetos (objetos. NET) y no solo flujos/texto.

Me gustaría poder usar PowerShell para llamar a métodos en mis assembies.NET (biblioteca C#).

¿Cómo hago referencia a un ensamblado en PowerShell y lo uso?

Author: Peter Mortensen, 2010-06-20

2 answers

Echa un vistazo a la entrada del blogCargar una DLL personalizada desde PowerShell:

Tomemos, por ejemplo, una biblioteca matemática simple. Tiene un método de suma estática y un método de producto de instancia:

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

Compilar y ejecutar en PowerShell:

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

> $mathInstance = new-object MyMathLib.Methods
> $mathInstance.Product(10, 2)
 44
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 17:21:06

Con PowerShell 2.0, puede usar el tipo de complemento del Cmdlet integrado.

Solo necesita especificar la ruta de acceso a la dll.

Add-Type -Path foo.dll

También, puede usar C # inline o VB.NET con Add-Type. La sintaxis @" es una cadena HERE.

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)
 47
Author: Andy Schneider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-21 00:23:21