Udostępnij za pomocą


Dodawanie i wywoływanie poleceń

Po utworzeniu obszaru uruchomieniowego można dodać polecenia i skrypty programu Windows PowerShell do potoku, a następnie wywołać potok synchronicznie lub asynchronicznie.

Tworzenie potoku

Klasa System.Management.Automation.PowerShell udostępnia kilka metod dodawania poleceń, parametrów i skryptów do potoku. Możesz wywołać potok synchronicznie, wywołując przeciążenie metody System.Management.Automation.PowerShell.Invoke* lub asynchronicznie przez wywołanie przeciążenia metody System.Management.Automation.PowerShell.BeginInvoke*, a następnie metody System.Management.Automation.PowerShell.EndInvoke*.

Dodajpolecenia

  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 wywołasz metodę System.Management.Automation.PowerShell.AddCommand* więcej niż raz przed wywołaniem metody System.Management.Automation.PowerShell.Invoke*, wynik pierwszego polecenia jest potokowy do drugiego polecenia itd. Jeśli nie chcesz potokować wyniku poprzedniego polecenia do polecenia, dodaj go, wywołując 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 System.Management.Automation.PSCommand.AddParameter* metodę Na przykład poniższy kod pobiera listę wszystkich procesów o nazwie powershell uruchomionych na maszynie.

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

Dodatkowe parametry można dodać, wywołując System.Management.Automation.PSCommand.AddParameter* wielokrotnie.

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

Możesz 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

Można symulować przetwarzanie wsadowe przy użyciu metody System.Management.Automation.PowerShell.AddStatement*, która dodaje dodatkową instrukcję na końcu potoku Poniższy kod pobiera listę uruchomionych procesów o nazwie powershell, a następnie pobiera listę uruchomionych 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 przyjęto założenie, że w folderze o nazwie D:\PSScriptsistnieje już skrypt o nazwie MyScript.ps1 .

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 ma wartość true, skrypt zostanie uruchomiony w zakresie lokalnym. Poniższy kod uruchomi skrypt w zakresie lokalnym.

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

Synchroniczne wywoływanie 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.
}

Wywoływanie potoku asynchronicznie

Potok jest wywoływany asynchronicznie przez wywołanie przeciążenia obiektu System.Management.Automation.PowerShell.BeginInvoke* w celu utworzenia obiektu IAsyncResult, a następnie wywołania metody System.Management.Automation.PowerShell.PowerInvoke*.

W poniższym przykładzie pokazano, jak asynchronicznie wywoływać potok.

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 InitialSessionState

Tworzenie ograniczonego obszaru runspace