Condividi tramite


Aggiunta e richiamo dei comandi

Dopo aver creato uno spazio di esecuzione, è possibile aggiungere comandi e script di Windows PowerShell a una pipeline e quindi richiamare la pipeline in modo sincrono o asincrono.

Creazione di una pipeline

La classe System.Management.Automation.PowerShell fornisce diversi metodi per aggiungere comandi, parametri e script alla pipeline. È possibile richiamare la pipeline in modo sincrono chiamando un overload del metodo System.Management.Automation.PowerShell.Invoke* o in modo asincrono chiamando un overload del metodo System.Management.Automation.PowerShell.BeginInvoke* e quindi metodo System.Management.Automation.PowerShell.EndInvoke*.

AddCommand

  1. Creare un oggetto System.Management.Automation.PowerShell.

    PowerShell ps = PowerShell.Create();
    
  2. Aggiungere il comando da eseguire.

    ps.AddCommand("Get-Process");
    
  3. Richiamare il comando.

    ps.Invoke();
    

Se si chiama il metodo System.Management.Automation.PowerShell.AddCommand* più volte prima di chiamare il metodo System.Management.Automation.PowerShell.Invoke*, il risultato del primo comando viene inviato tramite pipe al secondo e così via. Se non si vuole inviare tramite pipe il risultato di un comando precedente a un comando, aggiungerlo chiamando invece il System.Management.Automation.PowerShell.AddStatement*.

AddParameter

Nell'esempio precedente viene eseguito un singolo comando senza parametri. È possibile aggiungere parametri al comando usando il metodo System.Management.Automation.PSCommand.AddParameter*, ad esempio, il codice seguente ottiene un elenco di tutti i processi denominati powershell in esecuzione nel computer.

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

È possibile aggiungere altri parametri chiamando System.Management.Automation.PSCommand.AddParameter* ripetutamente.

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

È anche possibile aggiungere un dizionario di nomi e valori di parametri chiamando il metodo 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

È possibile simulare l'invio in batch usando il metodo System.Management.Automation.PowerShell.AddStatement*, che aggiunge un'istruzione aggiuntiva alla fine della pipeline. Il codice seguente ottiene un elenco di processi in esecuzione con il nome powershelle quindi ottiene l'elenco dei servizi in esecuzione.

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

AddScript

È possibile eseguire uno script esistente chiamando il metodo System.Management.Automation.PowerShell.AddScript*. Nell'esempio seguente viene aggiunto uno script alla pipeline ed eseguito. In questo esempio si presuppone che esista già uno script denominato MyScript.ps1 in una cartella denominata D:\PSScripts.

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

È disponibile anche una versione del metodo System.Management.Automation.PowerShell.AddScript* che accetta un parametro booleano denominato useLocalScope. Se questo parametro è impostato su true, lo script viene eseguito nell'ambito locale. Il codice seguente eseguirà lo script nell'ambito locale.

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

Richiamare una pipeline in modo sincrono

Dopo aver aggiunto elementi alla pipeline, richiamarlo. Per richiamare la pipeline in modo sincrono, chiamare un overload del metodo System.Management.Automation.PowerShell.Invoke*. L'esempio seguente illustra come richiamare in modo sincrono una pipeline.

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

Richiamare una pipeline in modo asincrono

Per richiamare una pipeline in modo asincrono, chiamare un overload del System.Management.Automation.PowerShell.BeginInvoke* per creare un oggetto IAsyncResult e quindi chiamare il metodo System.Management.Automation.PowerShell.EndInvoke*.

L'esempio seguente illustra come richiamare una pipeline in modo asincrono.

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

Vedere anche

Creazione di un InitialSessionState

Creazione di uno spazio di esecuzione vincolato