2009-04-20 62 views
3

我想要一個Win32進程來啓動外部腳本並能夠檢索它返回的ERRORLEVEL。獲取批處理腳本錯誤代碼

另一種方式很簡單。只需使用退出(errorcode)返回錯誤碼;在您的Win32應用程序和調用腳本獲取其正確設置ERRORLEVEL值。

但是,從一個Win32調用應用程序,獲取腳本errorcode是不完全相同的。我試着使用CreateProcess()並調用GetExitCodeProcess(),但它總是返回0而不是實際的ERRORLEVEL值。即使我結束我叫腳本退出%ERRORLEVEL%

我最好的猜測是,腳本是每說一個過程。最有可能的是CMD.EXE正在運行,而且最有可能總是以ExitCode爲0結尾。我知道ERRORLEVEL與進程ExitCode值不同,我希望CMD.EXE能夠鏡像它。

編輯:

對不起,我問了!我剛剛發現MY問題。我在我的批處理文件中使用了exit/b errorcode而不是退出錯誤代碼。看起來,/ 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% 

而且我通過我的腳本作爲參數來運行入口點腳本。其他「子腳本」文件可以調用exit/b或退出,因爲所有內容都被覆蓋了。

回答

1

這個工作對我來說:

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; 
} 
-1

嘗試通過以此爲lpCommandLine參數CreateProcess

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

這將打開延遲environment variable expansion(否則%ERRORLEVEL%執行<script_name>前擴展),並明確地返回由腳本作爲cmd.exe「返回的ERRORLEVEL s返回碼。

1

在黑暗中只是一個鏡頭(因爲我在家裏和周圍有沒有窗戶):

我們使用'cmd /c call <script>'工作。也許它適用於你的問題。

+0

哼哼...不錯的一個。我錯過了,因爲我沒有「打電話」而嘗試,並沒有奏效。 – 2009-04-20 19:20:03