Runspace01 – exempel
Det här exemplet visar hur du använder klassen System.Management.Automation.Powershell för att köra cmdleten Get-Process synkront. Cmdleten Get-Process returnerar System.Diagnostics.Process-objekt för varje process som körs på den lokala datorn. Värdena för egenskaperna System.Diagnostics.Process.Processname* och System.Diagnostics.Process.Handlecount* extraheras sedan från de returnerade objekten och visas i ett konsolfönster.
Krav
Det här exemplet kräver Windows PowerShell 2.0.
Demonstrationer
Skapa ett System.Management.Automation.Powershell-objekt för att köra ett kommando.
Lägga till ett -kommando i pipelinen för objektet System.Management.Automation.Powershell.
Köra kommandot synkront.
Använda System.Management.Automation.PSObject-objekt för att extrahera egenskaper från de objekt som returneras av kommandot.
Exempel
Det här exemplet kör cmdleten Get-Process synkront i standardkörningsutrymmet som tillhandahålls av 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();
}
}
}
Se även
Feedback
Skicka och visa feedback för