Vbs脚本可以在CMD上正常工作,但不能在Code中

时间:2019-07-03 10:39:26

标签: c# .net cmd vbscript

当我通过代码执行脚本时,它会陷入无限循环。但是相同的脚本可以在CMD中工作

尝试使用CMD并且可以正常工作,但不能在代码中工作。以任何VB脚本为例并进行验证。

    private string excecuteScript(string retValue)
    {
        try
        {
            string filetoexecute = Path.Combine(Application.StartupPath, Path.GetExtension(ScriptName).EndsWith(".vbs",StringComparison.InvariantCultureIgnoreCase) ? "AA_MyVB.vbs" : "AA_MyJS.js");
            filetoexecute = string.Format("\"" + filetoexecute + "\"");

            string arguments = " " + filetoexecute + " " + ScriptInputPara + " \"" + ScriptName + "\" ";

            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                FileName = Path.Combine(Environment.SystemDirectory, "WScript.exe"),
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            var myProcess = CommonMethods.InvokeProcess(startInfo);

            StreamReader errorStream = myProcess.StandardError;
            StreamReader outputStream = myProcess.StandardOutput;
            string theOutput = string.Empty;

            bool stopWhile = false;
            while (!stopWhile)
            {
                stopWhile = myProcess.HasExited;
                if (CmdTask.IsTaskTimedout)
                {
                    stopWhile = true;
                    myProcess.Kill();
                }
            }
            theOutput += outputStream.ReadLine();

            TheError += errorStream.ReadToEnd();

            if (myProcess.ExitCode != 0)
            {
                TheError = "Error occurred while executing script file";
            }

            if (IsScriptTask && !string.IsNullOrEmpty(theOutput) && !string.IsNullOrEmpty(ScriptOutputPara))
                CmdTask.SetVariableValue(ScriptOutputPara, theOutput);

        }
        catch (Exception ex)
        {
            retValue = (ex.Message);
        }

        return retValue;
    }

实际:myProcess.HasExited返回false

预期:myProcess.HasExited返回true

如果我在while循环之前执行theOutput += outputStream.ReadLine();,则myProcess.HasExited返回true ...

0 个答案:

没有答案