例如:
我有一个VBS代码,它会帮我检查程序是否已经运行
Function isProcessRunning(strComputer, strProcess)
Dim Process, strObject
strObject = "winmgmts://" & strComputer
For Each Process In GetObject(strObject).InstancesOf("Win32_Process")
If UCase(Process.Name) = UCase(strProcess) Then
isProcessRunning = True
Exit Function
Else
isProcessRunning = False
End If
Next
End Function
但是,我想让进程已经在重新使用。
Function shell()
If isProcessRunning(".", "cmd.exe") == False Then
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
shell = objShell.Run(cmd)
Else
shell = ... 'how can I get cmd.exe already running here
End If
Next
End Function
更新我的问题
实际上,我想获取cmd.exe
的实例,如果它已经在运行的话。我的意思是,我不想再次重新开放cmd.exe
。
示例:
cmd.exe
。laucher.vbs
)。Function isProcessRunning(strComputer, strProcess)
Dim Process, strObject
strObject = "winmgmts://" & strComputer
For Each Process In GetObject(strObject).InstancesOf("Win32_Process")
If UCase(Process.Name) = UCase(strProcess) Then
isProcessRunning = True
Exit Function
Else
isProcessRunning = False
End If
Next
End Function
Function getProcessRunning(strComputer, strProcess)
Dim Process, strObject
strObject = "winmgmts://" & strComputer
For Each Process In GetObject(strObject).InstancesOf("Win32_Process")
If UCase(Process.Name) = UCase(strProcess) Then
... 'I do not know how to code this here for return instance of Process is running ...
Exit Function
End If
Next
End Function
Function shell()
If isProcessRunning(".", "cmd.exe") == False Then
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
shellFn = objShell.Run("cmd")
Else
shellFn = getProcessRunning(".", "cmd.exe")
End If
End Function
Dim cmdExe
cmdExe = shell
cmdExe "shutdown -s -t 60"
由于cmd.exe
已在运行cmdExe "shutdown -s -t 60"
,因此将重新使用cmd并执行命令。
答案 0 :(得分:2)
试试这个例子:
Option Explicit
Dim ProcessPath1,ProcessPath2
ProcessPath1 = "%windir%\system32\cmd.exe"
ProcessPath2 = "%ProgramFiles%\Internet Explorer\iexplore.exe"
Call CheckProcess(ProcessPath1)
Call CheckProcess(ProcessPath2)
'**************************************************************************
Sub CheckProcess(ProcessPath)
Dim strComputer,objWMIService,colProcesses,WshShell,Tab,ProcessName
strComputer = "."
Tab = Split(ProcessPath,"\")
ProcessName = Tab(UBound(Tab))
ProcessName = Replace(ProcessName,Chr(34),"")
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 DblQuote(ProcessPath)
Else
MsgBox DblQuote(ProcessName) & " is aleardy running !", vbExclamation,_
DblQuote(ProcessName) & " is aleardy running !"
Exit Sub
End if
End Sub
'**************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**************************************************************************