QTP使用异步VBS进程并通过系统环境变量传值

在脚本执行过程中,有些程序会启动一些额外的进程来辅助完成一些特殊的功能,例如启动打印机。而某些进程会导致QTP的死锁。因此,我们需要通过一个异步的VBS文件扫描系统进程并结束。另外, 通过创建一个临时的系统环境变量来完成QTP向外部VBS传值。

在QTP中的代码如下:

'Set a new variable in system environment and start external VBScript 
Function StartKillProcess(strProcess)
	Set oShell = CreateObject("WScript.Shell")
	set oEnv = oShell.Environment("System")
	oEnv("Process_to_Kill") = strProcess
	oShell.Run "wscript.exe " & "C:\KillProcess.vbs"
	set oEnv = nothing
	Set oShell =  nothing
End Function


'Cancel the external VBScript and clear the temp system environment variable
Function EndKillProcess
	Const strComputer = "." 
	Dim objWMIService, colProcessList
	Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name ='wscript.exe'")
	For Each objProcess in colProcessList 
		objProcess.Terminate() 
	Next
	Set oShell = CreateObject("WScript.Shell")
	set oEnv=oShell.Environment("System")
	oEnv.Remove "Process_to_Kill"
	set oEnv = nothing
	Set oShell =  nothing
End function


'launch an excel process
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = true

'start async backend process
StartKillProcess "EXCEL.EXE"

'wait for the backend process killing
wait 3
 
'stop the backend process
EndKillProcess


在外部VBS中的代码如下:

function Kill_Process(strProcessName)
	Const strComputer = "." 
	Dim objWMIService, colProcessList
	Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Do	
		on error resume next
			Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name ='" & strProcessName & "'")
			For Each objProcess in colProcessList 
				objProcess.Terminate() 
			Next
			if err.number <> 0 then err.clear
		on error goto 0 
	loop
end function

set WshShell = CreateObject("WScript.Shell")
set oEnv=WshShell.Environment("System")
Process_to_Kill = oEnv("Process_to_Kill")
set WshShell = Nothing
set oEnv=nothing
strResult = Kill_Process(Process_to_Kill)




你可能感兴趣的:(vbs,asynchronous,qtp)