Crear un proyecto en Visual C# Biblioteca de Clase (.NET Framework)
Importar desde Microsoft Visual C# la referencia al ensamblado System.Management.Automation (C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll)
Añadir el siguiente código en PowerShell a Visual Studio C# y compilar la solución
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Management.Automation; // Windows PowerShell namespace. namespace PowerSh { public class PowerSh { public static void CrearUsuario() { //Create a PowerShell object. PowerShell ps = PowerShell.Create(); //New-LocalUser usuario -Password (ConvertTo-SecureString "11234aaadsf" -asplaintext -force) ps.AddScript("New-LocalUser usuario -Password (ConvertTo-SecureString '11234aaadsf' -asplaintext -force)"); IAsyncResult result = ps.BeginInvoke(); // do something else until execution has completed. // this could be sleep/wait, or perhaps some other work while (result.IsCompleted == false) { } } // End Main. } // End HostPs1. } |
La dll compilada se encuentra en la carpeta bin
Llamar a la dll creada desde PowerShell
1 2 |
[Reflection.Assembly]::LoadFile("C:\Users\juan\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll") [PowerSh.PowerSh]::CrearUsuario() |