How to Invoke a Pipeline Synchronously

This example shows how to invoke a pipeline synchronously. In this example, the host application defines input data, synchronously invokes a pipeline that contains the Sort-Object cmdlet, and then displays the sorted data at the command line.

The host application described in the following procedure can be implemented as a console application by using Microsoft Visual Studio.

To invoke a pipeline synchronously

  1. By using Visual Studio, create a new Console Application project.

  2. With the project open, add a reference to the System.Management.Automation.dll assembly.

    noteNote:
    • For Windows XP and Windows Vista operating systems, the assembly is located in the Windows PowerShell installation directory ($PSHome).

    • For Windows 7 operating systems, the assembly is located in the following folder: Windows\assembly\GAC_MSIL\System.Management.Automation.

  3. Add a using statement that references the System.Management.Automation namespace, and remove the default using statements that are not needed. The following statements are the only using statements that are needed for this host application.

  4. Within the Main method of the host application class, call the Create and AddCommand methods to create the pipeline.

  5. Call the Invoke method to run the pipeline synchronously. This method provides the input data that is used by the first command of the pipeline.

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

For an example of a host application that invokes the commands of the pipeline asynchronously, see How to Invoke a Pipeline Asynchronously.

Example

This example defines a set of input data, creates a pipeline that contains the Sort-Object cmdlet, and then invokes the pipeline synchronously on the local computer.

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

See Also



Show:
© 2014 Microsoft