이 샘플에서는 System.Management.Automation.PowerShell 클래스를 사용하여 Get-Process 실행하고 Sort-Object cmdlet을 동기적으로 방법을 보여 줍니다.
Get-Process cmdlet은 로컬 컴퓨터에서 실행되는 각 프로세스에 대해 System.Diagnostics.Process 개체를 반환하고 Sort-ObjectSystem.Diagnostics.Process.Id* 속성에 따라 개체를 정렬합니다. 이러한 명령의 결과는 System.Windows.Forms.DataGridView 컨트롤을 사용하여 표시됩니다.
요구 사항
이 샘플에는 Windows PowerShell 2.0이 필요합니다.
입증합니다
이 샘플에서는 다음을 보여 줍니다.
명령을 실행할 System.Management.Automation.PowerShell 개체를 만듭니다.
System.Management.Automation.PowerShell 개체의 파이프라인에 명령을 추가합니다.
명령을 동기적으로 실행합니다.
System.Windows.Forms.DataGridView 컨트롤을 사용하여 Windows Forms 애플리케이션에서 명령의 출력을 표시합니다.
예시
이 샘플에서는 Windows PowerShell에서 제공하는 기본 runspace에서 Get-Process 및 sort-Object cmdlet을 동기적으로 실행합니다. 출력은 System.Windows.Forms.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
/// and Sort-Object cmdlets synchronously. Windows Forms and
/// data binding are then used to display the results in a
/// DataGridView control.
/// </summary>
/// <param name="args">The parameter is 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 commands in a Windows Forms application.
/// </remarks>
private static void Main(string[] args)
{
Runspace02.CreateForm();
}
}
}
또한 참조하십시오
PowerShell