首页 > 解决方案 > Vbs 脚本可以在 CMD 中正常工作,但在代码中不能正常工作

问题描述

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

尝试使用 CMD 并且它可以工作但不能在代码中工作。以任意 VB Script 为例进行验证。

    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

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

标签: c#.netcmdvbscript

解决方案


推荐阅读