如何使用VB脚本检查进程是否正在运行?

时间:2015-10-06 06:59:20

标签: vbscript

我有以下VB脚本打开一个特定的窗口,在窗口中执行某些功能。

WScript.Sleep 10000
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "Notepad"
#perform some function

WScript.Sleep 10000

当记事本关闭时我需要重复相同的代码,以便再次打开相同的记事本。我为此目的尝试了以下代码

WScript.Sleep 10000
Set WshShell = WScript.CreateObject("WScript.Shell")
If (WshShell.AppActivate("Notepad") = False) then
ret = True
End If
Do while ret 
WshShell.Run "notepad"
WScript.Sleep 100
WshShell.AppActivate "Notepad"

loop

但即使之前的记事本没有关闭,此代码也会继续打开记事本。

1 个答案:

答案 0 :(得分:1)

你可以这样试试:

Option Explicit
Dim ProcessPath
ProcessPath = "%Windir%\System32\Notepad.exe"
Call CheckProcess(DblQuote(ProcessPath))
'**************************************************************************
Sub CheckProcess(ProcessPath)
    Dim strComputer,objWMIService,colProcesses,WshShell,Tab,ProcessName
    strComputer = "."
    Tab = Split(ProcessPath,"\")
    ProcessName = Tab(UBound(Tab))
    ProcessName = Replace(ProcessName,Chr(34),"")
    'Msgbox ProcessName
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = '"& ProcessName & "'")
    If colProcesses.Count = 0 Then
        Set WshShell = CreateObject("WScript.Shell")
        WshShell.Run ProcessPath
    Else
        Exit Sub
    End if
End Sub
'**************************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'**************************************************************************

或者这样:

Option Explicit
Dim ProcessPath,WshShell
ProcessPath = "%Windir%\System32\Notepad.exe"
Set WshShell = CreateObject("WScript.Shell")
If CheckProcess(DblQuote(ProcessPath)) = False Then
    WshShell.Run ProcessPath
End If  
'**************************************************************************
Function CheckProcess(ProcessPath)
    Dim strComputer,objWMIService,colProcesses,Tab,ProcessName
    strComputer = "."
    Tab = Split(ProcessPath,"\")
    ProcessName = Tab(UBound(Tab))
    ProcessName = Replace(ProcessName,Chr(34),"")
    'Msgbox ProcessName
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = '"& ProcessName & "'")
    If colProcesses.Count = 0 Then
        CheckProcess = False
    Else
        CheckProcess = True
    End if
End Function
'**************************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'**************************************************************************