解决“System.Diagnostics.Process调用批处理运行powershell.exe”的问题

问题场景:

在一个ASP.NET程序中,需要调用一个命令行下的bat(批处理)程序完成一些操作,而在该bat程序中又要调用powershell.exe -command运行powershell代码。

示例代码如下:

powershell.exe -command "[xml]$config = Get-Content repositories.config; "

如何在ASP.NET中调用bat程序员,请参考:在ASP.NET中运行控制台程序

调用bat的部分代码:

ProcessStartInfo info = new ProcessStartInfo();
info.WorkingDirectory
= workingDirectory;
info.CreateNoWindow
= true;
info.RedirectStandardOutput
= true;
info.RedirectStandardInput
= true;
info.RedirectStandardError
= true;
info.UseShellExecute
= false;

System.Diagnostics.Process p
= new Process();
p.StartInfo
= info;
p.Start();
output.Append(p.StandardOutput.ReadToEnd());
p.WaitForExit();
p.Close();

遇到的问题:

通过System.Diagnostics.Process执行bat之后,不能正常退出,也就是上面代码中的p.WaitForExit()一直在等待bat退出。

从浏览器看,浏览器一直处于“等待服务器返回”状态。

在服务器上,通过任务管理器可以看到一个powershell.exe进程一直存在。强制结束这个进程,浏览器就能得到正常返回。

解决方案:

根据以前的经验判断,应该是powershell.exe处于等待输入状态,开始不知道如何让powershell.exe退出这个状态。后来在stackoverflow找到很简单的解决方法,只要增加4个字符“<NUL”,bat文件改为如下代码,问题就解决了:

powershell.exe -command "[xml]$config = Get-Content repositories.config; " < NUL
posted @ 2011-08-23 19:19  dudu  阅读(3481)  评论(2编辑  收藏  举报