Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Este exemplo mostra como usar a classe System.Management.Automation.PowerShell para executar o cmdlet Get-Process de forma síncrona. O cmdlet Get-Process retorna objetos System.Diagnostics.Process para cada processo em execução no computador local. Os valores das propriedades System.Diagnostics.Process.ProcessName* e System.Diagnostics.Process.HandleCount* são extraídos dos objetos retornados e exibidos em uma janela do console.
Requerimentos
Este exemplo requer o Windows PowerShell 2.0.
Demonstra
Criando um objeto System.Management.Automation.PowerShell para executar um comando.
Adicionar um comando ao pipeline do objeto System.Management.Automation.PowerShell .
Executando o comando de forma síncrona.
Usando objetos System.Management.Automation.PSObject para extrair propriedades dos objetos retornados pelo comando.
Exemplo
Este exemplo executa o cmdlet Get-Process de forma síncrona no espaço de execução padrão fornecido pelo 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();
}
}
}