Dodawanie i wywoływanie poleceń

Po utworzeniu środowiska uruchomieniowego można dodać Windows poleceń i skryptów programu PowerShell do potoku, a następnie wywoływać potok synchronicznie lub asynchronicznie.

Tworzenie potoku

Klasa System.Management.Automation.Powershell udostępnia kilka metod dodawania poleceń, parametrów i skryptów do potoku. Potok można wywołać synchronicznie, wywołując przeciążenie metody System.Management.Automation.Powershell.Invoke* lub asynchronicznie, wywołując przeciążenie metody System.Management.Automation.Powershell.Begininvoke*, a następnie metodę System.Management.Automation.Powershell.Endinvoke*.

Dodajcommand

  1. Utwórz obiekt System.Management.Automation.Powershell.

    PowerShell ps = PowerShell.Create();
    
  2. Dodaj polecenie, które chcesz wykonać.

    ps.AddCommand("Get-Process");
    
  3. Wywołaj polecenie .

    ps.Invoke();
    

Jeśli metoda System.Management.Automation.Powershell.Addcommand* zostanie wywołana więcej niż raz przed wywołaniem metody System.Management.Automation.Powershell.Invoke*, wynik pierwszego polecenia zostanie potokowany do drugiego i tak dalej. Jeśli nie chcesz potokować wyniku poprzedniego polecenia do polecenia, dodaj go, wywołując zamiast tego polecenie System.Management.Automation.Powershell.Addstatement*.

AddParameter

W poprzednim przykładzie jest wykonywane pojedyncze polecenie bez żadnych parametrów. Parametry można dodać do polecenia przy użyciu metody System.Management.Automation.Pscommand.Addparameter*. Na przykład poniższy kod pobiera listę wszystkich procesów o nazwach uruchomionych na PowerShell maszynie.

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

Dodatkowe parametry można dodać wielokrotnie, wywołując element System.Management.Automation.Pscommand.Addparameter*.

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

Można również dodać słownik nazw parametrów i wartości, wywołując metodę 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

Przetwarzanie wsadowe można symulować przy użyciu metody System.Management.Automation.Powershell.Addstatement*, która dodaje dodatkową instrukcje na końcu potoku. Poniższy kod pobiera listę uruchomionych procesów o nazwie , a następnie pobiera listę uruchomionych PowerShell usług.

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

AddScript

Istniejący skrypt można uruchomić, wywołując metodę System.Management.Automation.Powershell.Addscript*. Poniższy przykład dodaje skrypt do potoku i uruchamia go. W tym przykładzie założono, że istnieje już skrypt o nazwie MyScript.ps1 w folderze o nazwie D:\PSScripts .

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

Istnieje również wersja metody System.Management.Automation.Powershell.Addscript*, która przyjmuje parametr logiczny o nazwie useLocalScope . Jeśli ten parametr jest ustawiony na true , skrypt jest uruchamiany w zakresie lokalnym. Poniższy kod spowoduje uruchomienie skryptu w zakresie lokalnym.

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

Synchroniczne wywołania potoku

Po dodaniu elementów do potoku należy go wywołać. Aby synchronicznie wywołać potok, należy wywołać przeciążenie metody System.Management.Automation.Powershell.Invoke*. W poniższym przykładzie pokazano, jak synchronicznie wywołać potok.

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

Asynchroniczne wywołania potoku

Potok wywołuje się asynchronicznie, wywołując przeciążenie metody System.Management.Automation.Powershell.Begininvoke*, aby utworzyć obiekt IAsyncResult, a następnie wywołując metodę System.Management.Automation.Powershell.Endinvoke*.

W poniższym przykładzie pokazano sposób asynchronicznego wywoływania potoku.

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

Zobacz też

Tworzenie elementu InitialSessionState

Tworzenie ograniczonego obszaru działania