如何修复错误“由于以下错误无法加载 PowerShell 管理单元 Microsoft.PowerShell.Diagnostics:无法加载文件或程序集”

Ril*_*ton 12 c# asp.net powershell

我正在尝试从 asp.net 网页执行 Powershell 脚本,但在尝试执行该脚本时,我不断收到此错误。我尝试了 2 种执行脚本的方法,但都给了我同样的错误。完整的错误是:

处理请求时出现未处理的异常 PSSnapInException:无法加载 PowerShell 管理单元 Microsoft.PowerShell.Diagnostics 由于以下错误:无法加载文件或程序集 'C:\source\repos\WebApp\WebApp\Microsoft.PowerShell.Commands '。该系统找不到指定的文件。

PowerShell powershell = PowerShell.Create();
            using (Runspace runspace = RunspaceFactory.CreateRunspace())
            {
                runspace.Open();
                powershell.Runspace = runspace;
                System.IO.StreamReader sr = new System.IO.StreamReader("C:\\Desktop\\test.ps1");
                powershell.AddScript(sr.ReadToEnd());
                var results = powershell.Invoke();
                if (powershell.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                }
            }
Run Code Online (Sandbox Code Playgroud)
    using (PowerShell PowerShellInstance = PowerShell.Create())
                {   
  PowerShellInstance.AddScript("C:\\Users\\RSpotton\\Desktop\\test.ps1");
                    PowerShellInstance.Invoke();
                }
Run Code Online (Sandbox Code Playgroud)

小智 30

我有一个类似的问题和伴随的错误消息。安装NuGet包Microsoft.PowerShell.SDK到我的项目并获得成功。

  • 就我而言,我必须卸载此软件包并安装旧版本(从 7.1 到 6.2.7)。其他相关软件包(例如 System.Management.Autoamtion)也是 6.2.7 (6认同)
  • 如果能更好地记录 C# 中 powershell 的使用情况,那就太好了。谢谢二进制伯尼。如果它对任何人有帮助,也可以在 github 问题中找到此记录:https://github.com/PowerShell/PowerShell/issues/2108 (3认同)