We might sometimes need to trigger a batch file which is on the server using .Net. I had to run batch files on server many times and i faced lot of issues while running them using asp.net and I finally got it right, so thought of sharing my code through this post.
For that First add reference to System.Diagnostics name space.
Then create a ProcessStartInfo object and set filename,arguments and WorkingDirectory properties of the same object as shown below.
using System.Diagnostics;
ProcessStartInfo psi = new ProcessStartInfo
{
Arguments = batchFile+ " >log.log",
FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
};
psi.WorkingDirectory = Path.GetDirectoryName(batchFile);
ProcessStartInfo psi = new ProcessStartInfo
{
Arguments = batchFile+ " >log.log",
FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
};
psi.WorkingDirectory = Path.GetDirectoryName(batchFile);
Please note >log.log is used to generate a log file (log file will be generated in same location where batch file is residing) and we are executing batch file using powershell rather than usual command prompt.
Next is to create a process object and set its StartInfo property to the ProcessStarInfo object which we created earlier.
Below code will do exactly that.
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.StartInfo = psi;
p.Start();
To sum up everything:
public static int RunBatch(string batchFile, int timeOut = 10000)
{
ProcessStartInfo psi = new ProcessStartInfo
{
Arguments = batchFile+ " >log.log",
FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
};
psi.WorkingDirectory = Path.GetDirectoryName(batchFile);
psi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit(timeOut); //or p.WaitForExit() to wait until batch completes processing completely.
return p.ExitCode;
}
Well there are some more properites you can set to redirect standard error and output. For instance:
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
string error=p.StandardError.ReadToEnd();
string output=p.StandardOutput.ReadToEnd();
Please note give full control to "NETWORKSERVICE" user on batch file in order to successfully execute batch file otherwise you may face access issues. Don't forget to disable impersonation in web.config file. Last but not least do not write pause statement in your batch file otherwise it will run forever :).

No comments:
Post a Comment