c# open runspace in background

p3ppi 1 Reputation point

I am trying to find a way into c#. The following program takes one argument as input, opens a runspace and invokes the argument, e.g. "powershell ls". Now I would like to have the program do its work in the background and not block the command line interface while it is executing so I could run two instances of it at the same time. What is the way to get there, if any? Can I somehow "fork" that runspace?

using System;  
using System.Text;  
using System.Management.Automation;  
using System.Management.Automation.Runspaces;  
using System.Collections.ObjectModel;  
namespace runspace  
    internal class Program  
        static void Main(string[] args)  
            void invokeCommand(string command)  
                Runspace runspace = RunspaceFactory.CreateRunspace();  
                RunspaceState state = runspace.RunspaceStateInfo.State;  
                Console.WriteLine("Runspace State = " + state);  
                Pipeline pipeline = runspace.CreatePipeline();  
                Collection<PSObject> results = pipeline.Invoke();  
                //List<PSObject> results = pipeline.Invoke().ToArray().ToList();  
                StringBuilder stringBuilder = new StringBuilder();  
                foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); }  
                String output = stringBuilder.ToString();  
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,281 Reputation points Microsoft Vendor

    @p3ppi , Welcome to Microsoft Q&A, you could refer to the following code to open two instances of runspace in background.


    Tested result:


    The first argument is used to get the current files information of the current folder, the second argument is used to get the current date.

    Best Regards,

    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments