【问题标题】:What is the reference for PowerShell in .NET?.NET 中 PowerShell 的参考是什么?
【发布时间】:2019-08-24 20:19:28
【问题描述】:

我尝试在 C# 中运行 PowerShell 脚本。但它会抛出错误:

PowerShell doesn't available in current context. 

我在谷歌上搜索过,但我没有得到解决方案,请帮忙。这是我的代码:

string text = System.IO.File.ReadAllText(@"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");    
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
    PowerShellInstance.AddScript(text);

    if (PowerShellInstance.Streams.Error.Count > 0)
    {
        Console.Write("Error");
    }
    Console.ReadKey();
}

【问题讨论】:

    标签: c# .net powershell namespaces


    【解决方案1】:

    您需要下载 System.Management.Automation 并将其附加到您的项目中:

    https://www.nuget.org/profiles/PowerShellTeam

    【讨论】:

    • 我已经安装了 System.Management.Automation.dll 。但错误未消除。
    • 您是否在命名空间上方引用了它? using System.Management.Automation;
    • 检查dll是否位于:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\...
    【解决方案2】:

    从 VS Nuget Manager 下载 System.Management.AutomationSystem.Management.Automation.Runspaces 的包并将其添加到您的项目中。

    https://powershell.org/forums/topic/executing-powershell-from-c/

    【讨论】:

      【解决方案3】:

      PowerShell 类存在于 Windows PowerShell SDK 1.1.0 中,您可以使用此 NuGet 包添加到您的项目中:https://www.nuget.org/packages/System.Management.Automation/

      PM> Install-Package System.Management.Automation -Version 6.2.0
      

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 2012-11-28
        • 1970-01-01
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-30
        • 2018-05-30
        相关资源
        最近更新 更多