现在的位置: 首页 > 综合 > 正文

使用wmi在vbs实现SingleInstance

2013年09月18日 ⁄ 综合 ⁄ 共 1099字 ⁄ 字号 评论关闭

在vbs脚本中,有时需要只运行一个实例。借助Wmi的强大功能,我们可以曲线实现这一功能。代码如下

  1. option explicit
  2. '主过程,在开始前监测是否脚本只有一个实例 
  3. main:Sub main()
  4.     If Not amISingle Then Exit Sub  ' 或者wscript.quit 
  5.     'do what's your want to do ..... 
  6.    '这里假设监视某个文件大小,若超过100字节就jjyy,有了singleInstance后,就可以保证不重复监视
  7.    Do while  true 
  8.         on error goto next 
  9.         if createobject("scripting.filesystemobject").getFile("abc.txt").size>100 then exit do
  10.        if err.number<>0 then exit do '这比用fileExists实在。。。。。
  11.         wscript.sleep 1000    '每1秒钟检测一次
  12.    loop 
  13.    msgbox "size overflow."
  14. End Sub 
  15. '脚本是否只存在单一实例 
  16. '[out]boolean amISingle:若脚本只有一个运行,返回True,否则False 
  17. function amISingle()
  18.     Dim objWmi,objProcs,objProc
  19.     Dim intCount:intCount=0  '运行中的本实例数目 
  20.     '获取wmi服务,注意,这里是getobject 
  21.     Set objWmi=getobject("winmgmts://./root/cimv2")  
  22.     '查询系统中所有名称为"wscript.shell"的进程 
  23.     set objProcs=objWmi.execQuery("select * from win32_Process where name='wscript.exe'"
  24.     '遍历,比较wscript.exe的运行参数,若其参数和这个脚本的路进相同,就记录 
  25.     For Each objProc In objProcs
  26.         If InStr(objProc.commandLine,wscript.scriptFullName)>0 Then intCount=intCount+1
  27.     Next 
  28.     amISingle=(intCount=1)
  29. end function 

抱歉!评论已关闭.