在vbs脚本中,有时需要只运行一个实例。借助Wmi的强大功能,我们可以曲线实现这一功能。代码如下
- option explicit
- '主过程,在开始前监测是否脚本只有一个实例
- main:Sub main()
- If Not amISingle Then Exit Sub ' 或者wscript.quit
- 'do what's your want to do .....
- '这里假设监视某个文件大小,若超过100字节就jjyy,有了singleInstance后,就可以保证不重复监视
- Do while true
- on error goto next
- if createobject("scripting.filesystemobject").getFile("abc.txt").size>100 then exit do
- if err.number<>0 then exit do '这比用fileExists实在。。。。。
- wscript.sleep 1000 '每1秒钟检测一次
- loop
- msgbox "size overflow."
- End Sub
- '脚本是否只存在单一实例
- '[out]boolean amISingle:若脚本只有一个运行,返回True,否则False
- function amISingle()
- Dim objWmi,objProcs,objProc
- Dim intCount:intCount=0 '运行中的本实例数目
- '获取wmi服务,注意,这里是getobject
- Set objWmi=getobject("winmgmts://./root/cimv2")
- '查询系统中所有名称为"wscript.shell"的进程
- set objProcs=objWmi.execQuery("select * from win32_Process where name='wscript.exe'")
- '遍历,比较wscript.exe的运行参数,若其参数和这个脚本的路进相同,就记录
- For Each objProc In objProcs
- If InStr(objProc.commandLine,wscript.scriptFullName)>0 Then intCount=intCount+1
- Next
- amISingle=(intCount=1)
- end function