2016-09-20 112 views
0

我正在使用wmic來執行一些遠程任務,但是,我不能強迫它等待完成。舉例如下:等待WMIC完成遠程調用

wmic process call create "cmd.exe /c ping 127.0.0.1 -n 10 > nul","C:\Data" 

wmic進程終止,而另一個cmd窗口正在休眠10秒。

我想讓wmic進程等待打開的cmd會話完成(即在這種情況下等待10秒)。這可能嗎?

更新:我在尋找一個非批處理解決方案

回答

1

下一個批處理腳本可以爲你工作:

@ECHO OFF >NUL 
SETLOCAL EnableExtensions DisableDelayedExpansion 

REM get the global process identifier 
set "_ProcessId=" 
for /F "tokens=*" %%G in (' 

    wmic process call create "cmd.exe /c ping 127.0.0.1 -n 10 > nul"^,"%temp%"^|find /I "ProcessId" 

') do for /F "tokens=1,2 delims=;= " %%g in ("%%~G") do set "_%%~g=%%~h" 

REM wait while the process is running 
If defined _ProcessId (
    call :waitForEnd 
) else (
    rem debugging output  echo NO process was created 
) 

ENDLOCAL 
goto :eof 

:waitForEnd 
    rem debugging output 
    echo waiting until [%_ProcessId%] terminates %time% 
    rem set appropriate number of seconds to wait in next timeout command 
    >NUL 2>&1 timeout /T 4 /NOBREAK 
    for /F "tokens=1 delims=:" %%G in (' 
     tasklist /FI "PID eq %_ProcessId%" /FO csv /NH 
    ') do if /I NOT [%%G]==[INFO] goto :waitForEnd 
    rem debugging output 
    echo  process [%_ProcessId%] terminated %time% 
goto :eof 

輸出

==> D:\bat\SO\39599427.bat 

waiting until [2420] terminates 23:24:52,77 
waiting until [2420] terminates 23:24:56,21 
waiting until [2420] terminates 23:25:00,20 
     process [2420] terminated 23:25:04,22 

==>