VBScript等待功能

时间:2015-07-29 16:00:23

标签: vbscript

我试图将此函数转换为等待notepad.exe到通用等待函数(可以等待任何进程)。我无法在不破坏语法的情况下在sQuery中添加变量,有没有办法绕过这个问题?

Function wait()
Set svc=getobject("winmgmts:root\cimv2")
sQuery="select * from win32_process where name='notepad.exe'"
Set cproc=svc.execquery(sQuery)
iniproc=cproc.count
Do While iniproc = 1
    wscript.sleep 5000
    set svc=getobject("winmgmts:root\cimv2")
    sQuery="select * from win32_process where name='notepad.exe'"
    set cproc=svc.execquery(sQuery)
    iniproc=cproc.count
Loop    
Set cproc=nothing
Set svc=Nothing
End Function

Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set wscr = CreateObject("Wscript.shell")
wscr.Run "notepad.exe"

wait()

MsgBox "done!"

我疯了!!

3 个答案:

答案 0 :(得分:1)

您用来启动记事本的WScript.Shell对象的Run方法有一个内置机制来等待进程完成。您根本不需要在脚本中使用基于WMI的wait()函数。

wscr.Run "notepad.exe", 1, True

该行末尾的True值表示Run()应该等待该过程完成。

但要回答您的具体问题,请在wait功能中添加一个参数。我叫它ProcessName。然后使用此变量而不是notepad.exe。当您调用wait()时,您将进程的名称指定为参数。

Function wait(ProcessName)
Set svc=getobject("winmgmts:root\cimv2")
sQuery="select * from win32_process where name='" & ProcessName & "'"
Set cproc=svc.execquery(sQuery)
iniproc=cproc.count
Do While iniproc = 1
    wscript.sleep 5000
    set svc=getobject("winmgmts:root\cimv2")
    sQuery="select * from win32_process where name='" & ProcessName & "'"
    set cproc=svc.execquery(sQuery)
    iniproc=cproc.count
Loop    
Set cproc=nothing
Set svc=Nothing
End Function

Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set wscr = CreateObject("Wscript.shell")
wscr.Run "notepad.exe"

wait("notepad.exe")

MsgBox "done!"

答案 1 :(得分:1)

回答 Patrick S. 然而,Do While循环中有两条超级行和两条不必要的行:

Function wait(sPName)
Set svc=getobject("winmgmts:root\cimv2")
sQuery="select * from win32_process where name='" & sPName & "'"
Set cproc=svc.execquery(sQuery)
iniproc=cproc.count
Do While iniproc > 0
    wscript.sleep 5000
    'superabundant' set svc=getobject("winmgmts:root\cimv2")
    'superabundant' sQuery="select * from win32_process where name='notepad.exe'"
    set cproc=svc.execquery(sQuery)
    iniproc=cproc.count
Loop    
'unnecessary' Set cproc=nothing
'unnecessary' Set svc=Nothing
End Function

Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set wscr = CreateObject("Wscript.shell")

sProcessName="calc.exe"
wscr.Run sProcessName
wait( sProcessName)
MsgBox "done " & sProcessName

wscr.Run "notepad.exe"
wait( "notepad.exe")
MsgBox "done notepad.exe"

答案 2 :(得分:0)

Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2") 
Set objEvents = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_ProcessTrace")
Do
    Set objReceivedEvent = objEvents.NextEvent
    If objReceivedEvent.ProcessName = "svchost.exe" then msgbox objReceivedEvent.ProcessName
'   msgbox objReceivedEvent.ProcessName
Loop

Win32_ProcessTrace(开始和停止),Win32_ProcessTraceStartWin32_ProcessTraceStop。脚本停止并等待事件发生。