Compartir a través de


Adición e invocación de comandos

Después de crear un espacio de ejecución, puede agregar Windows comandos y scripts de PowerShell a una canalización y, a continuación, invocar la canalización de forma sincrónica o asincrónica.

Creación de una canalización

La clase System.Management.Automation.Powershell proporciona varios métodos para agregar comandos, parámetros y scripts a la canalización. Puede invocar la canalización sincrónicamente llamando a una sobrecarga del método System.Management.Automation.Powershell.Invoke* o de forma asincrónica llamando a una sobrecarga del método System.Management.Automation.Powershell.Begininvoke* y, a continuación, al método System.Management.Automation.Powershell.Endinvoke*.

AddCommand

  1. Cree un objeto System.Management.Automation.Powershell.

    PowerShell ps = PowerShell.Create();
    
  2. Agregue el comando que desea ejecutar.

    ps.AddCommand("Get-Process");
    
  3. Invoque el comando .

    ps.Invoke();
    

Si llama al método System.Management.Automation.Powershell.Addcommand* más de una vez antes de llamar al método System.Management.Automation.Powershell.Invoke*, el resultado del primer comando se canalizará al segundo, etc. Si no desea canalizar el resultado de un comando anterior a un comando, agrégrelo llamando a System.Management.Automation.Powershell.Addstatement* en su lugar.

AddParameter

En el ejemplo anterior se ejecuta un único comando sin parámetros. Puede agregar parámetros al comando mediante el método System.Management.Automation.Pscommand.Addparameter*. Por ejemplo, el código siguiente obtiene una lista de todos los procesos denominados que se ejecutan en la PowerShell máquina.

PowerShell.Create().AddCommand("Get-Process")
                   .AddParameter("Name", "PowerShell")
                   .Invoke();

Puede agregar parámetros adicionales llamando repetidamente a System.Management.Automation.Pscommand.Addparameter*.

PowerShell.Create().AddCommand("Get-Command")
                   .AddParameter("Name", "Get-VM")
                   .AddParameter("Module", "Hyper-V")
                   .Invoke();

También puede agregar un diccionario de nombres de parámetros y valores llamando al método System.Management.Automation.Powershell.Addparameters*.

IDictionary parameters = new Dictionary<String, String>();
parameters.Add("Name", "Get-VM");

parameters.Add("Module", "Hyper-V");
PowerShell.Create().AddCommand("Get-Command")
   .AddParameters(parameters)
      .Invoke()

AddStatement

Puede simular el procesamiento por lotes mediante el método System.Management.Automation.Powershell.Addstatement*, que agrega una instrucción adicional al final de la canalización. El código siguiente obtiene una lista de procesos en ejecución con el nombre y, a continuación, obtiene la lista de servicios en PowerShell ejecución.

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process").AddParameter("Name", "PowerShell");
ps.AddStatement().AddCommand("Get-Service");
ps.Invoke();

AddScript

Puede ejecutar un script existente llamando al método System.Management.Automation.Powershell.Addscript*. En el ejemplo siguiente se agrega un script a la canalización y se ejecuta. En este ejemplo se supone que ya hay un script denominado MyScript.ps1 en una carpeta denominada D:\PSScripts .

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();

También hay una versión del método System.Management.Automation.Powershell.Addscript* que toma un parámetro booleano denominado useLocalScope . Si este parámetro se establece en true , el script se ejecuta en el ámbito local. El código siguiente ejecutará el script en el ámbito local.

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1"), true).Invoke();

Invocación sincrónica de una canalización

Después de agregar elementos a la canalización, invoquelo. Para invocar la canalización de forma sincrónica, llame a una sobrecarga del método System.Management.Automation.Powershell.Invoke*. En el ejemplo siguiente se muestra cómo invocar sincrónicamente una canalización.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;

namespace HostPS1e
{
  class HostPS1e
  {
    static void Main(string[] args)
    {
      // Using the PowerShell.Create and AddCommand
      // methods, create a command pipeline.
      PowerShell ps = PowerShell.Create().AddCommand ("Sort-Object");

      // Using the PowerShell.Invoke method, run the command
      // pipeline using the supplied input.
      foreach (PSObject result in ps.Invoke(new int[] { 3, 1, 6, 2, 5, 4 }))
      {
          Console.WriteLine("{0}", result);
      } // End foreach.
    } // End Main.
  } // End HostPS1e.
}

Invocación asincrónica de una canalización

Para invocar una canalización de forma asincrónica, llame a una sobrecarga del objeto System.Management.Automation.Powershell.Begininvoke* para crear un objeto IAsyncResult y, a continuación, llame al método System.Management.Automation.Powershell.Endinvoke*.

En el ejemplo siguiente se muestra cómo invocar una canalización de forma asincrónica.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;

namespace HostPS3
{
  class HostPS3
  {
    static void Main(string[] args)
    {
      // Use the PowerShell.Create and PowerShell.AddCommand
      // methods to create a command pipeline that includes
      // Get-Process cmdlet. Do not include spaces immediately
      // before or after the cmdlet name as that will cause
      // the command to fail.
      PowerShell ps = PowerShell.Create().AddCommand("Get-Process");

      // Create an IAsyncResult object and call the
      // BeginInvoke method to start running the
      // command pipeline asynchronously.
      IAsyncResult asyncpl = ps.BeginInvoke();

      // Using the PowerShell.Invoke method, run the command
      // pipeline using the default runspace.
      foreach (PSObject result in ps.EndInvoke(asyncpl))
      {
        Console.WriteLine("{0,-20}{1}",
                result.Members["ProcessName"].Value,
                result.Members["Id"].Value);
      } // End foreach.
      System.Console.WriteLine("Hit any key to exit.");
      System.Console.ReadKey();
    } // End Main.
  } // End HostPS3.
}

Consulte también

Creación de un InitialSessionState

Creación de un espacio de ejecución restringido