How to call PowerShell cmdlets from C# in Visual Studio

前端 未结 1 720
春和景丽
春和景丽 2020-12-19 22:24

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 runnin

相关标签:
1条回答
  • 2020-12-19 23:02

    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?

    0 讨论(0)
提交回复
热议问题