c# open runspace in background

p3ppi 1 Reputation point
2022-08-31T21:22:12.233+00:00

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();  
                runspace.Open();  
                RunspaceState state = runspace.RunspaceStateInfo.State;  
                Console.WriteLine("Runspace State = " + state);  
  
                Pipeline pipeline = runspace.CreatePipeline();  
                pipeline.Commands.AddScript(command);  
                Collection<PSObject> results = pipeline.Invoke();  
                 
                runspace.Close();  
                //List<PSObject> results = pipeline.Invoke().ToArray().ToList();  
                StringBuilder stringBuilder = new StringBuilder();  
                foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); }  
                String output = stringBuilder.ToString();  
                Console.WriteLine(output);  
                Console.WriteLine("Ende");  
            }  
  
            invokeCommand(args[0]);  
  
            //Console.ReadLine();  
        }  
    }  
}  
C#
C#
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
    2022-09-01T01:58:18.653+00:00

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

    code.txt

    Tested result:

    236723-image.png

    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,
    Jack


    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