I have a big issue with executing vbscript with C#. I have this generic process execution function:
/// <summary>
/// Runs a process silent (Without DOS window) with the given arguments and returns the process' exit code.
/// </summary>
/// <param name="output">Recieves the output of either std/err or std/out</param>
/// <param name="exe">The executable to run, may be unqualified or contain environment variables</param>
/// <param name="args">The list of unescaped arguments to provide to the executable</param>
/// <returns>Returns process' exit code after the program exits</returns>
/// <exception cref="System.IO.FileNotFoundException">Raised when the exe was not found</exception>
/// <exception cref="System.ArgumentNullException">Raised when one of the arguments is null</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Raised if an argument contains '\0', '\r', or '\n'</exception>
public static int Run(Action<string> output, string exe, params string[] args)
{
if (String.IsNullOrEmpty(exe))
throw new FileNotFoundException();
if (output == null)
throw new ArgumentNullException("output");
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
psi.ErrorDialog = false;
psi.WorkingDirectory = Environment.CurrentDirectory;
psi.FileName = FindExePath(exe);
psi.Arguments = args[0];
using (Process process = Process.Start(psi))
using (ManualResetEvent mreOut = new ManualResetEvent(false),
mreErr = new ManualResetEvent(false))
{
process.OutputDataReceived += (o, e) => { if (e.Data == null) mreOut.Set(); else output(e.Data); };
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) => { if (e.Data == null) mreErr.Set(); else output(e.Data); };
process.BeginErrorReadLine();
process.WaitForExit();
mreOut.WaitOne();
mreErr.WaitOne();
return process.ExitCode;
}
}
Works like charme. Now I want to execute a vbscript with this function. I call it like this:
int exit_code = ProcessUtility.Run(output_action, "cscript.exe", "//Nologo" + save_parameter_string);
This also runs very well, but my problem is, it runs a littlebit to good. If I execute an vbscript which contains an error, the exit code is also "0" ;( The output contains the correct "exception" from vbscript, in my case: "...\test.vbs(145, 12) Runtime error in Microsoft VBScript: Object neccesarry" but the exit code is 0.
Does anyone have an idea, why?