简体   繁体   中英

Error running PS in .NetCore app - Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'Broken'

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM