等待WMIC完成远程呼叫

时间:2016-09-20 16:32:51

标签: windows 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秒)。这可能吗?

更新:我正在寻找非批量解决方案

2 个答案:

答案 0 :(得分: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

==>

答案 1 :(得分:0)

我发现JosefZ的注释很有用,但是等待循环仅在您在运行脚本的服务器上本地启动进程时才有效。就我而言,我需要在其他服务器上启动一个进程,然后等待它完成。

通过添加/ NODE:开关,您可以远程启动该过程。这意味着现在要读取任务列表,您需要远程运行该任务列表,而我能弄清楚的将其读回脚本的唯一方法是将输出写入文件然后通过文件共享读取的笨拙方法。 / p>

:waitForEnd
echo waiting until [%_ProcessID%] terminates %time%  >> %logfile%
>NUL 2>&1 timeout /T 30 /NOBREAK
wmic /NODE:"RemoteServerName" process call create "cmd /c F:\Scripts\Batch\ProcMon.bat %_ProcessId%"
for /F "tokens=1 delims=:" %%G in (
    \\<remoteServerName>\<ShareName>\procmon.log
) do if /I NOT [%%G]==[INFO] goto :waitForEnd
echo process [%_ProcessID%] terminated at %time%  >> %logfile%

:: wrap-up
echo %date% %time% "Processing completed" >> %logfile%
ENDLOCAL
goto:eof

然后在远程服务器上,下面是F:\ Scripts \ Batch \ ProcMon.bat:

tasklist /FI "PID eq %1" /FO csv /NH > F:\Scripts\Batch\procmon.log