Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
In diesem Beispiel wird gezeigt, wie Sie die System.Management.Automation.PowerShell Klasse verwenden, um das cmdlet Get-Process- synchron auszuführen. Das Cmdlet Get-Process gibt System.Diagnostics.Process Objekte für jeden Prozess zurück, der auf dem lokalen Computer ausgeführt wird. Die Werte der System.Diagnostics.Process.ProcessName* und System.Diagnostics.Process.HandleCount* Eigenschaften werden dann aus den zurückgegebenen Objekten extrahiert und in einem Konsolenfenster angezeigt.
Anforderungen
In diesem Beispiel ist Windows PowerShell 2.0 erforderlich.
Veranschaulichung
Erstellen eines System.Management.Automation.PowerShell- Objekts zum Ausführen eines Befehls.
Hinzufügen eines Befehls zur Pipeline des System.Management.Automation.PowerShell-Objekts.
Synchrones Ausführen des Befehls.
Verwenden von System.Management.Automation.PSObject Objekte zum Extrahieren von Eigenschaften aus den vom Befehl zurückgegebenen Objekten.
Beispiel
In diesem Beispiel wird das cmdlet Get-Process- synchron im standardmäßigen Runspace ausgeführt, der von Windows PowerShell bereitgestellt wird.
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();
}
}
}