Agregar e invocar comandos
Después de crear un espacio de ejecución, puede agregar comandos y scripts de Windows PowerShell a una canalización y luego invocar la canalización de forma sincrónica o asincrónica.
Creando una tubería
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 de forma sincrónica llamando a una sobrecarga del método System.Management.Automation.Powershell.Invoke*, o de forma asincrónica llamando a una sobrecarga del System.Management.Automation.Powershell.Begininvoke* y luego a System.Management.Automation Método .Powershell.Endinvoke*.
AddCommand
Cree un objeto System.Management.Automation.Powershell.
PowerShell ps = PowerShell.Create();Agregue el comando que desea ejecutar.
ps.AddCommand("Get-Process");Invoca 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 canaliza al segundo, y así sucesivamente. Si no desea canalizar el resultado de un comando anterior a un comando, agréguelo llamando a System.Management.Automation.Powershell.Addstatement*.
AddParameter
El ejemplo anterior ejecuta un único comando sin ningún parámetro. Puede agregar parámetros al comando utilizando el método System.Management.Automation.Pscommand.Addparameter*. Por ejemplo, el siguiente código obtiene una lista de todos los procesos denominados PowerShell que se ejecutan en la máquina. .
PowerShell.Create().AddCommand("Get-Process")
.AddParameter("Name", "PowerShell")
.Invoke();
Puede agregar parámetros adicionales llamando a System.Management.Automation.Pscommand.Addparameter* repetidamente.
PowerShell.Create().AddCommand("Get-Command")
.AddParameter("Name", "Get-VM")
.AddParameter("Module", "Hyper-V")
.Invoke();
También puede agregar un diccionario de nombres y valores de parámetros 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 utilizando el método System.Management.Automation.Powershell.Addstatement*, que agrega una declaración adicional al final de la canalización. El siguiente código obtiene una lista de procesos en ejecución con el nombre PowerShell y luego obtiene la lista de servicios en 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*. El siguiente ejemplo agrega un script a la canalización y lo ejecuta. Este ejemplo supone que ya existe un script llamado MyScript.ps1 en una carpeta llamada D:\PSScripts.
PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();
También existe 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, entonces el script se ejecuta en el ámbito local. El siguiente código ejecutará el script en el ámbito local.
PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1"), true).Invoke();
Invocar una canalización sincrónicamente
Después de agregar elementos a la canalización, la invoca. Para invocar la canalización sincrónicamente, se llama a una sobrecarga del método System.Management.Automation.Powershell.Invoke*. El siguiente ejemplo 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.
}
Invocar una canalización de forma asincrónica
Para invocar una canalización de forma asincrónica, llama a una sobrecarga de System.Management.Automation.Powershell.Begininvoke* para crear un objeto IAsyncResult y luego llama al método System.Management.Automation.Powershell.Endinvoke*.
El siguiente ejemplo 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.
}
Ver también
Crear un estado de sesión inicial
Crear un espacio de ejecución restringido