当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] Runspace01 示例

作者:精品下载站 日期:2024-12-14 02:45:25 浏览:13 分类:玩电脑

Runspace01 示例


此示例演示如何使用 System.Management.Automation.Powershell 类同步运行 Get-Process cmdlet。 Get-Process cmdlet 返回本地计算机上运行的每个进程的 System.Diagnostics.Process 对象。然后从返回的对象中提取 System.Diagnostics.Process.Processname* 和 System.Diagnostics.Process.Handlecount* 属性的值并显示在控制台窗口中。

要求

此示例需要 Windows PowerShell 2.0。

示范

  • 创建 System.Management.Automation.Powershell 对象来运行命令。

  • 将命令添加到 System.Management.Automation.Powershell 对象的管道。

  • 同步运行命令。

  • 使用 System.Management.Automation.PSObject 对象从命令返回的对象中提取属性。

例子

此示例在 Windows PowerShell 提供的默认运行空间中同步运行 Get-Process cmdlet。

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();
    }
  }
}

参见

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯