3

I'm trying to implement a .NetCore 3.1 console app which needs to run PowerShell scripts. However, when I try run it, I get the following error -

Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'Broken'.

The code that runs the PS script is as below:

        using System.Management.Automation;

        public async Task<string> RunScript(string scriptToRun)
        {
            // create a new hosted PowerShell instance using the default runspace.
            using PowerShell ps = PowerShell.Create();

            // specify the script code to run.
            ps.AddScript(scriptToRun);

            // execute the script and await the result.
            var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);

            // print the resulting pipeline objects to the console.
            var output = new StringBuilder();
            foreach (var item in pipelineObjects)
            {
                output.Append(item.BaseObject.ToString());
            }

            return output.ToString();
        }

Any idea what could be the issue?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Siva
  • 43
  • 4

1 Answers1

1

Resolved this by creating custom runspace. Refer to this article - How to run powershell core scripts from net core applications

Siva
  • 43
  • 4