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

[玩转系统] Runspace02 (C#) 代码示例

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

Runspace02 (C#) 代码示例


以下是 Runspace02 示例的 C# 源代码。此示例使用 System.Management.Automation.Runspaceinvoke 类同步执行 Get-Process cmdlet。然后使用 Windows 窗体和数据绑定在 DataGridView 控件中显示结果

代码示例

namespace Microsoft.Samples.PowerShell.Runspaces
{
  using System;
  using System.Collections;
  using System.Collections.ObjectModel;
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;
  using System.Windows.Forms;
  using PowerShell = System.Management.Automation.PowerShell;

  /// <summary>
  /// This class contains the Main entry point for this host application.
  /// </summary>
  internal class Runspace02
  {
    /// <summary>
    /// This method creates the form where the output is displayed.
    /// </summary>
    private static void CreateForm()
    {
      Form form = new Form();
      DataGridView grid = new DataGridView();
      form.Controls.Add(grid);
      grid.Dock = DockStyle.Fill;

      // 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())
      {
        powershell.AddCommand("get-process").AddCommand("sort-object").AddArgument("ID");
        if (Runspace.DefaultRunspace == null)
        {
          Runspace.DefaultRunspace = powershell.Runspace;
        }
        
        Collection<PSObject> results = powershell.Invoke();
        
        // The generic collection needs to be re-wrapped in an ArrayList
        // for data-binding to work.
        ArrayList objects = new ArrayList();
        objects.AddRange(results);
        
        // The DataGridView will use the PSObjectTypeDescriptor type
        // to retrieve the properties.
        grid.DataSource = objects;
      }
      
      form.ShowDialog();
    }
    
    /// <summary>
    /// This sample uses a PowerShell object to run the 
    /// Get-Process cmdlet synchronously. Windows Forms and 
    /// data binding are then used to display the results in a
    /// DataGridView control.
    /// </summary>
    /// <param name="args">Parameter not used.</param>
    /// <remarks>
    /// This sample demonstrates the following:
    /// 1. Creating a PowerShell object.
    /// 2. Adding commands and arguments to the pipeline of 
    ///    the powershell object.
    /// 3. Running the commands synchronously.
    /// 4. Using a DataGridView control to display the output 
    ///    of the PowerShell object in a Windows Forms application. 
    /// </remarks>
    private static void Main(string[] args)
    {
      Runspace02.CreateForm();
    }
  }
}

参见

Windows PowerShell SDK

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

取消回复欢迎 发表评论:

关灯