Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Cet exemple montre comment utiliser la classe System.Management.Automation.PowerShell pour exécuter l’applet de commande Get-Process de manière synchrone. L’applet de commande Get-Process retourne objets System.Diagnostics.Process pour chaque processus s’exécutant sur l’ordinateur local. Les valeurs des propriétés System.Diagnostics.Process.ProcessName* et System.Diagnostics.Process.HandleCount* sont ensuite extraites des objets retournés et affichées dans une fenêtre de console.
Spécifications
Cet exemple nécessite Windows PowerShell 2.0.
Montre ce qui suit
Création d’un objet System.Management.Automation.PowerShell pour exécuter une commande.
Ajout d’une commande au pipeline de l’objet System.Management.Automation.PowerShell.
Exécution de la commande de manière synchrone.
À l’aide de Objets System.Management.Automation.PSObject pour extraire les propriétés des objets retournés par la commande.
Exemple :
Cet exemple exécute l'applet de commande Get-Process de manière synchrone dans l’instance d’exécution par défaut fournie par Windows 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();
}
}
}