.NET中PowerShell的参考是什么?

时间:2019-04-03 10:23:53

标签: c# .net powershell namespaces

我试图在C#中运行PowerShell脚本。但这会引发错误:

PowerShell doesn't available in current context. 

我在Google中进行了搜索,但没有得到解决方案,请提供帮助。这是我的代码:

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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