Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How can I run multiple powershell commands in a C#/powershell runspace?

How can I run multiple powershell commands in a C#/powershell runspace?

Scheduled Pinned Locked Moved C#
questioncsharpwindows-admintutorial
8 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    turbosupramk3
    wrote on last edited by
    #1

    For example the code below

    Pipeline pipeline = runspacee.CreatePipeline();

    pipeline.Commands.Add(command1);
    pipeline.Commands.Add(command2);

    var exResults = pipeline.Invoke();

    powershell.AddCommand("set-adserversettings")
    .AddParameter("viewentireforest", true)
    .AddParameter(";");

    powershell.AddCommand("set-userphoto")
    .AddParameter("Identity", tbxName.Text)
    .AddParameter("picturedata", displayedImage)
    .AddParameter("DomainController", "12-34-56-01.XXX.XXX.XXXX.XXX")
    .AddParameter("confirm ", false)
    .AddParameter(";");

    L 1 Reply Last reply
    0
    • T turbosupramk3

      For example the code below

      Pipeline pipeline = runspacee.CreatePipeline();

      pipeline.Commands.Add(command1);
      pipeline.Commands.Add(command2);

      var exResults = pipeline.Invoke();

      powershell.AddCommand("set-adserversettings")
      .AddParameter("viewentireforest", true)
      .AddParameter(";");

      powershell.AddCommand("set-userphoto")
      .AddParameter("Identity", tbxName.Text)
      .AddParameter("picturedata", displayedImage)
      .AddParameter("DomainController", "12-34-56-01.XXX.XXX.XXXX.XXX")
      .AddParameter("confirm ", false)
      .AddParameter(";");

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      ... and your question is?

      T 1 Reply Last reply
      0
      • L Lost User

        ... and your question is?

        T Offline
        T Offline
        turbosupramk3
        wrote on last edited by
        #3

        How can I run the code above in C#? I can run single powershell commands, but nothing requiring multiple commands such as the example code I posted. For example, I could run set-userphoto, but if I have to import a module or set-adserversettings, I cannot get that to work?

        L 1 Reply Last reply
        0
        • T turbosupramk3

          How can I run the code above in C#? I can run single powershell commands, but nothing requiring multiple commands such as the example code I posted. For example, I could run set-userphoto, but if I have to import a module or set-adserversettings, I cannot get that to work?

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          What is contained in command1 and command2 in your code snippet? And what results or errors do you see?

          T 1 Reply Last reply
          0
          • L Lost User

            What is contained in command1 and command2 in your code snippet? And what results or errors do you see?

            T Offline
            T Offline
            turbosupramk3
            wrote on last edited by
            #5

            I should have removed the command1 and command2, those were just additional ways of me trying the same thing. Sorry about that. Error message is

            Quote:

            - The term 'Import-Module' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. - System.Management.Automation - at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable input, PSDataCollection`1 output, PSInvocationSettings settings) at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings) at System.Management.Automation.PowerShell.Invoke(IEnumerable input) at System.Management.Automation.RemotePipeline.Invoke(IEnumerable input) at System.Management.Automation.Runspaces.Pipeline.Invoke() at exchangePictureUpdater.exchangePictureUpdater.btnAddReplace_Click(Object sender, EventArgs e) - Void CoreInvoke[TOutput](System.Collections.IEnumerable, System.Management.Automation.PSDataCollection`1[TOutput], System.Management.Automation.PSInvocationSettings) |

            Command command1 = new Command("set-adserversettings");
            CommandParameter parameter1 = new CommandParameter("viewentireforest", true);
            command1.Parameters.Add(parameter1);

            Command command2 = new Command("set-userphoto");
            CommandParameter parameter2a = new CommandParameter("identity", tbxName.Text);
            CommandParameter parameter2b = new CommandParameter("picturedata", displayedImage);
            CommandParameter parameter2c = new CommandParameter("domaincontroller", "adfadfadf.com");
            CommandParameter parameter2d = new CommandParameter("confirm", false);
            command2.Parameters.Add(parameter2a);
            command2.Parameters.Add(parameter2b);
            command2.Parameters.Add(parameter2c);
            command2.Parameters.Add(parameter2d);

            Pipeline pipeline = runspacee.CreatePipeline();

            pipeline.Commands.Add(command1);
            pipeline.Commands.Add(command2);

            L 1 Reply Last reply
            0
            • T turbosupramk3

              I should have removed the command1 and command2, those were just additional ways of me trying the same thing. Sorry about that. Error message is

              Quote:

              - The term 'Import-Module' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. - System.Management.Automation - at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable input, PSDataCollection`1 output, PSInvocationSettings settings) at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings) at System.Management.Automation.PowerShell.Invoke(IEnumerable input) at System.Management.Automation.RemotePipeline.Invoke(IEnumerable input) at System.Management.Automation.Runspaces.Pipeline.Invoke() at exchangePictureUpdater.exchangePictureUpdater.btnAddReplace_Click(Object sender, EventArgs e) - Void CoreInvoke[TOutput](System.Collections.IEnumerable, System.Management.Automation.PSDataCollection`1[TOutput], System.Management.Automation.PSInvocationSettings) |

              Command command1 = new Command("set-adserversettings");
              CommandParameter parameter1 = new CommandParameter("viewentireforest", true);
              command1.Parameters.Add(parameter1);

              Command command2 = new Command("set-userphoto");
              CommandParameter parameter2a = new CommandParameter("identity", tbxName.Text);
              CommandParameter parameter2b = new CommandParameter("picturedata", displayedImage);
              CommandParameter parameter2c = new CommandParameter("domaincontroller", "adfadfadf.com");
              CommandParameter parameter2d = new CommandParameter("confirm", false);
              command2.Parameters.Add(parameter2a);
              command2.Parameters.Add(parameter2b);
              command2.Parameters.Add(parameter2c);
              command2.Parameters.Add(parameter2d);

              Pipeline pipeline = runspacee.CreatePipeline();

              pipeline.Commands.Add(command1);
              pipeline.Commands.Add(command2);

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Where does that occur?

              T 1 Reply Last reply
              0
              • L Lost User

                Where does that occur?

                T Offline
                T Offline
                turbosupramk3
                wrote on last edited by
                #7

                results = pipeline.Invoke() I need a working example of how to do this, and after that I can modify it to my own needs

                T 1 Reply Last reply
                0
                • T turbosupramk3

                  results = pipeline.Invoke() I need a working example of how to do this, and after that I can modify it to my own needs

                  T Offline
                  T Offline
                  turbosupramk3
                  wrote on last edited by
                  #8

                  Here is what I ended up doing, this allows me to create a script in a string with multiple commands, it processes 1 command at a time and then creates a runspace in c# and runs all of the powershell commands

                  string scriptText = @"$pw = convertto-securestring -AsPlainText -Force -String ''; $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist '\', $pw; $session = new-pssession -ConfigurationName Microsoft.Exchange -ConnectionUri '/powershell' -credential $cred; import-pssession $session; Set-ExecutionPolicy bypass -confirm:$false -force; $pic = ([System.IO.File]::ReadAllBytes('" + + "')); set-userphoto -identity -picturedata $pic -domaincontroller '' -confirm:$false;";

                              runExchangeShellScript(scriptText);
                  

                  private string runExchangeShellScript(string scriptText)
                  {

                          Runspace runspace = RunspaceFactory.CreateRunspace();
                  
                          // open it
                          runspace.Open();
                  
                          // create a pipeline and feed it the script text
                          Pipeline pipeline = runspace.CreatePipeline();
                          pipeline.Commands.AddScript(scriptText);
                          RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                          runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
                  
                          // add an extra command to transform the script output objects into nicely formatted strings
                          // remove this line to get the actual objects that the script returns. For example, the script
                          // "Get-Process" returns a collection of System.Diagnostics.Process instances.
                          //pipeline.Commands.Add("Out-String");
                  
                          // execute the script
                          Collection<PSObject> results = null;
                          try
                          {
                              results = pipeline.Invoke();
                          }
                          catch (Exception ex)
                          {
                              MessageBox.Show(ex.InnerException + " - " + ex.Message + " - " + ex.Source + " - " + ex.StackTrace + " - " + ex.TargetSite + " - " + ex.Data);
                              return "";
                          }
                  
                  
                          // close the runspace
                          runspace.Close();
                  
                          // convert the script result into a single string
                          StringBuilder stringBuilder = new StringBuilder();
                          foreach (PSObject ob
                  
                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups