我试图使用C#编写一个PowerShell脚本来运行我的应用程序。问题是,如果我使用C#运行它,脚本无法正常工作;但是,如果我手动运行它,则可以完成工作。
以下是脚本:
NuGet:System.Management.Automation
以下是脚本:
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!");
}
我使用了这里的示例。
注意:我的应用程序以管理员身份运行。
PowerShellInstance.HadErrors
。如果为真,则检查异常的PowerShellInstance.InvocationStateInfo.Reason
,如果为空,则检查非终止错误记录的PowerShellInstance.Streams.Error
。如果这些都不能提供所需的信息,则PowerShellInstance.EndInvoke(result)
将给出命令的输出。 - Patrick Meinecke