Partager via


Ajout et appel de commandes

Après avoir créé un runspace, vous pouvez ajouter des commandes et des scripts Windows PowerShell à un pipeline, puis appeler le pipeline de manière synchrone ou asynchrone.

Création d’un pipeline

La classe System.Management.Automation.PowerShell fournit plusieurs méthodes pour ajouter des commandes, des paramètres et des scripts au pipeline. Vous pouvez appeler le pipeline de manière synchrone en appelant une surcharge de la méthode System.Management.Automation.PowerShell.Invoke*, ou en appelant de manière asynchrone une surcharge du System.Management.Automation.PowerShell.BeginInvoke*, puis la méthode System.Management.Automation.PowerShell.EndInvoke*.

AddCommand

  1. Créez un objet System.Management.Automation.PowerShell.

    PowerShell ps = PowerShell.Create();
    
  2. Ajoutez la commande que vous souhaitez exécuter.

    ps.AddCommand("Get-Process");
    
  3. Appelez la commande.

    ps.Invoke();
    

Si vous appelez la méthode System.Management.Automation.PowerShell.AddCommand* plusieurs fois avant d’appeler la méthode System.Management.Automation.PowerShell.Invoke*, le résultat de la première commande est redirigé vers le deuxième, etc. Si vous ne souhaitez pas diriger le résultat d’une commande précédente vers une commande, ajoutez-la en appelant l'System.Management.Automation.PowerShell.AddStatement* à la place.

AddParameter

L’exemple précédent exécute une seule commande sans aucun paramètre. Vous pouvez ajouter des paramètres à la commande à l’aide de la méthode System.Management.Automation.PSCommand.AddParameter* Par exemple, le code suivant obtient une liste de tous les processus nommés powershell en cours d’exécution sur l’ordinateur.

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

Vous pouvez ajouter des paramètres supplémentaires en appelant System.Management.Automation.PSCommand.AddParameter* à plusieurs reprises.

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

Vous pouvez également ajouter un dictionnaire de noms et de valeurs de paramètres en appelant la méthode 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

Vous pouvez simuler le traitement par lots à l’aide de la méthode System.Management.Automation.PowerShell.AddStatement*, qui ajoute une instruction supplémentaire à la fin du pipeline Le code suivant obtient une liste de processus en cours d’exécution avec le nom powershell, puis obtient la liste des services en cours d’exécution.

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

AddScript

Vous pouvez exécuter un script existant en appelant la méthode System.Management.Automation.PowerShell.AddScript*. L’exemple suivant ajoute un script au pipeline et l’exécute. Cet exemple suppose qu’il existe déjà un script nommé MyScript.ps1 dans un dossier nommé D:\PSScripts.

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

Il existe également une version de la méthode System.Management.Automation.PowerShell.AddScript* qui accepte un paramètre booléen nommé useLocalScope. Si ce paramètre est défini sur true, le script est exécuté dans l’étendue locale. Le code suivant exécute le script dans l’étendue locale.

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

Appel d’un pipeline de manière synchrone

Après avoir ajouté des éléments au pipeline, vous l’appelez. Pour appeler le pipeline de façon synchrone, vous appelez une surcharge de la méthode System.Management.Automation.PowerShell.Invoke*. L’exemple suivant montre comment appeler de façon synchrone un 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.
}

Appel asynchrone d’un pipeline

Vous appelez un pipeline de manière asynchrone en appelant une surcharge du System.Management.Automation.PowerShell.BeginInvoke* pour créer un objet IAsyncResult, puis en appelant la méthode System.Management.Automation.PowerShell.EndInvoke*.

L’exemple suivant montre comment appeler un pipeline de façon asynchrone.

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

Voir aussi

Création d’un InitialSessionState

Création d’une d’espace d’exécution contrainte