このサンプルでは、System.Management.Automation.PowerShell クラスを使用して、Get-Process コマンドレットを同期的に実行する方法を示します。 Get-Process コマンドレットは、ローカル コンピューターで実行されている各プロセス 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 コマンドレットを同期的に実行します。
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();
}
}
}
こちらもご覧ください
PowerShell