Use WMI to implement singleinstance in vbs

Source: Internet
Author: User

In a vbs script, you sometimes need to run only one instance. With the powerful features of WMI, we can achieve this function by curve. The Code is as follows:

  1. Option explicit
  2. 'Main process: Check whether the script has only one instance before it starts.
  3. Main: Sub main ()
  4. If not amisingle then exit sub 'or wscript. Quit
  5. 'Do what's your want to do .....
  6. 'Assume that the file size is monitored. If the size of a file exceeds 100 bytes, jjyy is used. With singleinstance, you can avoid repeated monitoring.
  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 ', which is more realistic than fileexists .....
  11. Wscript. Sleep 1000 'detected every 1 second
  12. Loop
  13. Msgbox "size overflow ."
  14. End sub
  15. 'Does the script only exist for a single instance?
  16. '[Out] Boolean amisingle: returns true if only one script is run; otherwise, false
  17. Function amisingle ()
  18. Dim ob1_mi, objprocs, objproc
  19. Dim intcount: intcount = 0' Number of running instances
  20. 'Retrieve the WMI Service. Note that this is GetObject.
  21. Set ob1_mi = GetObject ("winmgmts: //./root/cimv2 ")
  22. 'Query a process named "wscript. Shell"
  23. Set objprocs1_ob1_mi.exe cquery ("select * From win32_process where name1_'wscript.exe '")
  24. Comparing the running parameters of wscript.exe, if the parameters are the same as those of the script
  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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.