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)




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章