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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值