Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Questo esempio illustra come usare classe System.Management.Automation.PowerShell per eseguire in modo sincrono il cmdlet Get-Process . Il cmdlet Get-Process restituisce oggetti System.Diagnostics.Process per ogni processo in esecuzione nel computer locale. I valori delle proprietà System.Diagnostics.Process.ProcessName* e System.Diagnostics.Process.HandleCount* vengono quindi estratti dagli oggetti restituiti e visualizzati in una finestra della console.
Requisiti
Questo esempio richiede Windows PowerShell 2.0.
Dimostra
Creazione di un oggetto System.Management.Automation.PowerShell per eseguire un comando.
Aggiunta di un comando alla pipeline dell'oggetto System.Management.Automation.PowerShell.
Esecuzione del comando in modo sincrono.
Utilizzando oggetti System.Management.Automation.PSObject per estrarre proprietà dagli oggetti restituiti dal comando.
Esempio
Questo esempio esegue il cmdlet get-process in modo sincrono nello spazio di esecuzione predefinito fornito da 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();
}
}
}