Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To execute PowerShell commands and scripts using an already existing PowerShell instance in C#, you can use the following steps:

  1. Import the Microsoft.PowerShell.Commands namespace and create a new PowerShell instance.
using System.Management.Automation;
PowerShell ps = PowerShell.Create();
  1. Pass the PowerShell script or command to the PowerShell instance and execute it.
ps.AddScript("Get-Process");
var results = ps.Invoke();
  1. Access the result of the PowerShell execution and manipulate it as necessary.
foreach (var result in results)
{
    Console.WriteLine(result.ToString());
}
  1. Close the PowerShell instance when you're finished.
ps.Dispose();

You can also use the PowerShell RunspacePool class to manage multiple PowerShell instances and configuration options.