从C#运行PowerShell脚本

6
我试图使用C#编写一个PowerShell脚本来运行我的应用程序。问题是,如果我使用C#运行它,脚本无法正常工作;但是,如果我手动运行它,则可以完成工作。
以下是脚本: DISM /online /Enable-Feature /Featurename:NetFx3 /All 该脚本在Windows服务器上启用Framework 3.5。来源 我的代码:
NuGet:System.Management.Automation
using (PowerShell PowerShellInstance = PowerShell.Create()) 
{ 
    PowerShellInstance.AddScript("DISM /online /Enable-Feature /Featurename:NetFx3 /All ");

    // begin invoke execution on the pipeline
    IAsyncResult result = PowerShellInstance.BeginInvoke();

    // do something else until execution has completed.
    // this could be sleep/wait, or perhaps some other work
    while (result.IsCompleted == false)
    {
        Console.WriteLine("Waiting for pipeline to finish...");
        Thread.Sleep(1000);

        // might want to place a timeout here...
    }

    Console.WriteLine("Finished!");
}

我使用了这里的示例。

注意:我的应用程序以管理员身份运行。


什么错误?尝试使用try-catch块进行包装。 - Daniel
没有错误,它没有启用3.5功能。几秒钟后,控制台会显示“完成”。 - Bad-Ass
2
检查PowerShellInstance.HadErrors。如果为真,则检查异常的PowerShellInstance.InvocationStateInfo.Reason,如果为空,则检查非终止错误记录的PowerShellInstance.Streams.Error。如果这些都不能提供所需的信息,则PowerShellInstance.EndInvoke(result)将给出命令的输出。 - Patrick Meinecke
1个回答

3
尝试将管理员权限添加到您的PowerShell脚本中,有时会有帮助。
PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File "$ScriptPath"' -Verb RunAs}"

您可以将PowerShell命令保存在ps1文件中,然后将路径作为参数($ScriptPath)提供。通过运行您指定的代码,测试了此PowerShell命令在C#上的使用。希望这可以帮到您。如果不行,则建议使用C# System.Diagnostics命名空间中的Process。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接