代码之家  ›  专栏  ›  技术社区  ›  Philibert Perusse

获取批处理脚本错误代码

  •  3
  • Philibert Perusse  · 技术社区  · 16 年前

    退出(错误代码) 返回错误码; 在Win32应用程序中,调用脚本将正确设置其ERRORLEVEL值。

    但是,从Win32调用应用程序获取脚本错误代码并不完全相同。

    我尝试使用CreateProcess()并调用GetExitCodeProcess(),但它总是返回0,而不是ERRORLEVEL的实际值。即使我以

    我最好的猜测是剧本是

    编辑:

    我的 退出/b错误代码 而不是 退出错误代码 在我的批处理文件中。当您从命令行进行测试时,/b选项的优点似乎是只关闭正在运行的脚本,而不是CMD.EXE。但是没有为CMD.EXE设置正确的ExitCode的缺点是。

    因此,对于子孙后代,我正在做的是:

    int LaunchScript(TCHAR *pCmdLineParam)
    {
        bool bResult;
        PROCESS_INFORMATION pi;
        STARTUPINFO si;
    
        memset(&si, 0, sizeof(si));
        si.cb = sizeof(si);
    
        TCHAR   cmdLine[256];
        _tcscpy(cmdLine,L"Test.cmd");
        _tcscat(cmdLine,L" ");
        _tcscat(cmdLine,pCmdLineParam);
    
        _tprintf(L"Process executing: %s\n",cmdLine);
    
        bResult = CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)?true:false;
        if (!bResult) {
            _tprintf(L"CreateProcess() error - %d", GetLastError());
            return -1;
        }
    
        DWORD result = WaitForSingleObject(pi.hProcess,15000);
        if( result == WAIT_TIMEOUT ) {
            return -2;
        }
    
        DWORD exitCode=0;
        if( !GetExitCodeProcess(pi.hProcess,&exitCode) ) {
            _tprintf(L"GetExitCodeProcess() error - %d", GetLastError());
            return -1;
        }
    
        _tprintf(L"Process exitcode=%d\n",exitCode);
    
        return exitCode;
    }
    

    @call %*
    @exit %ERRORLEVEL%
    

    3 回复  |  直到 16 年前
        1
  •  1
  •   cookre    16 年前

    这对我很有用:

    int DoDOS(string parms)
    {
    
    Process p=new Process();
    ProcessStartInfo ProcInfo=new ProcessStartInfo();
    
    ProcInfo.Arguments="/C "+parms;
    ProcInfo.CreateNoWindow=true;
    ProcInfo.ErrorDialog=false;
    ProcInfo.ErrorDialogParentHandle=IntPtr.Zero;
    ProcInfo.FileName="cmd.exe";
    ProcInfo.RedirectStandardError=false;
    ProcInfo.RedirectStandardInput=false;
    ProcInfo.RedirectStandardOutput=false;
    ProcInfo.UseShellExecute=false;
    ProcInfo.Verb="";
    ProcInfo.WindowStyle=ProcessWindowStyle.Hidden;
    p=Process.Start(ProcInfo);
    
    while (!p.HasExited)
          {
          if (laRunning.Text!=RunningTxt) laRunning.Text=RunningTxt;
          else                            laRunning.Text="";
          Application.DoEvents();
          Thread.Sleep(500);
          }
    
    return p.ExitCode; 
    }
    
        2
  •  1
  •   Tilo Prütz    16 年前

    我们使用 'cmd /c call <script>'

        3
  •  -1
  •   Rômulo Ceccon    16 年前

    lpCommandLine 参数 CreateProcess

    cmd /v:on /k <script_name> & exit !errorlevel!
    

    它会打开的 environment variable expansion (否则 %ERRORLEVEL% 在执行之前展开 <script_name> )并显式返回 ERRORLEVEL cmd.exe 的返回代码。