Search code examples
vbscriptwin32-process

Run a cmd.exe which calls a bat file and wait to finish


I need to be able to run cmd.exe with special privilege to run a bat file and wait until it finishes.

I already managed to open cmd.exe with special privilege but I cannot find a wait until the bat file finishes. I cannot use WScript.Shell because cmd.exe is opened with special privilege using cimv2.

Dim WMIObj, strHost, intProcessID

On Error Resume Next

strHost = "."

Set WMIObj = GetObject("winmgmts:\\" & strHost & "\root\cimv2:Win32_Process")
If IsObject(WMIObj) Then
    WMIObj.Security_.Privileges.AddAsString "SeRestorePrivilege", True
    WMIObj.Create "cmd.exe /c cd /d c:\temp && asd.cmd && pause", Null, Null, intProcessID
End If

Set WMIObj = Nothing

Solution

  • Add a loop to wait until the process with PID intProcessID disappears:

    Set wmi = GetObject("winmgmts://./root/cimv2")
    Do
      WScript.Sleep 100
      Set p = wmi.ExecQuery("SELECT * FROM W32_Process WHERE ProcessID=" & intProcessID)
    Until p.Count = 0