I'm creating a PowerShell cmdlets from Visual Studio and I can't find out how to call cmdlets from within my C# file, or if this is even possible? I have no trouble running my cmdlets one by one, but I want to set up a cmdlet to run multiple cmdlets in a sequel.
Asked
Active
Viewed 5,882 times
7
-
1See also [*Invoking powershell cmdlets from C#*](https://stackoverflow.com/questions/17067971/invoking-powershell-cmdlets-from-c-sharp). – Franklin Yu Nov 20 '18 at 20:58
1 Answers
11
Yes, you can call cmdlets from your C# code.
You'll need these two namespaces:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
Open a runspace:
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
Create a pipeline:
Pipeline pipeline = runSpace.CreatePipeline();
Create a command:
Command cmd= new Command("APowerShellCommand");
You can add parameters:
cmd.Parameters.Add("Property", "value");
Add it to the pipeline:
pipeline.Commands.Add(cmd);
Run the command(s):
Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
....do stuff with psObject (output to console, etc)
}
Does this answer your question?
tnw
- 12,952
- 15
- 68
- 109
-
1Shouldn't pipeline.Commands.Add(getProcess); be pipeline.Commands.Add(cmd); - otherwise what looks like a pretty good answer. – simon at rcl Jan 21 '14 at 16:57
-
-
Despite its age this is still a very helpful answer. For those using dotnet core and the CLI, begin with `dotnet add package system.management.automation` to get those namespaces. – Peter Wone Jul 13 '20 at 03:43
-
1Sorry that's not the core package, for Core you need `microsoft.powershell.sdk` – Peter Wone Jul 13 '20 at 04:34
-
This is to run existing PowerShell cmdlets. Is there a way to run a custom cmdlet (implemented in C#) using automation API? – Ehsan Keshavarzian Nov 29 '21 at 05:16