繁体   English   中英

在 .NetCore 应用程序中运行 PS 时出错 - 无法执行操作,因为运行空间未处于“已打开”状态。 运行空间的当前状态是“已损坏”

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

我正在尝试实现一个需要运行 PowerShell 脚本的 .NetCore 3.1 控制台应用程序。 但是,当我尝试运行它时,出现以下错误 -

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

运行PS脚本的代码如下:

        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();
        }

知道可能是什么问题吗?

通过创建自定义运行空间解决了这个问题。 参考这篇文章 - 如何从网络核心应用程序运行 powershell 核心脚本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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