Runspace01 (C#) 代码示例

下面是 创建运行指定命令的控制台应用程序中所述的运行空间的代码示例。 为此,应用程序调用一个运行空间,然后调用一个命令。 (请注意,此应用程序不指定运行空间配置信息,也不会显式创建管道)。 调用的命令是 Get-Process cmdlet。

注释

可以使用适用于 Windows Vista 的 Microsoft Windows 软件开发工具包和 Microsoft .NET Framework 3.0 运行时组件下载此运行空间的 C# 源文件(runspace01.cs)。 有关下载说明,请参阅 如何安装 Windows PowerShell 并下载 Windows PowerShell SDK <PowerShell 示例> 目录中提供了下载的源文件。

代码示例

namespace Microsoft.Samples.PowerShell.Runspaces
{
  using System;
  using System.Management.Automation;
  using PowerShell = System.Management.Automation.PowerShell;
  
  /// <summary>
  /// This class contains the Main entry point for this host application.
  /// </summary>
  internal class Runspace01
  {
    /// <summary>
    /// This sample uses the PowerShell class to execute
    /// the get-process cmdlet synchronously. The name and
    /// handlecount are then extracted from the PSObjects
    /// returned and displayed.
    /// </summary>
    /// <param name="args">Parameter not used.</param>
    /// <remarks>
    /// This sample demonstrates the following:
    /// 1. Creating a PowerShell object to run a command.
    /// 2. Adding a command to the pipeline of the PowerShell object.
    /// 3. Running the command synchronously.
    /// 4. Using PSObject objects to extract properties from the objects
    ///    returned by the command.
    /// </remarks>
    private static void Main(string[] args)
    {
      // Create a PowerShell object. Creating this object  takes care of 
      // building all of the other data structures needed to run the command.
      using (PowerShell powershell = PowerShell.Create().AddCommand("get-process"))
      {
        Console.WriteLine("Process              HandleCount");
        Console.WriteLine("--------------------------------");
          
        // Invoke the command synchronously and display the  
        // ProcessName and HandleCount properties of the 
        // objects that are returned.
        foreach (PSObject result in powershell.Invoke())
        {
          Console.WriteLine(
                      "{0,-20} {1}",
                      result.Members["ProcessName"].Value,
                      result.Members["HandleCount"].Value);
        }
      }
      
      System.Console.WriteLine("Hit any key to exit...");
      System.Console.ReadKey();
    }
  }
}

另请参阅

Windows PowerShell 程序员指南

Windows PowerShell SDK