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:
- Option explicit
- 'Main process: Check whether the script has only one instance before it starts.
- Main: Sub main ()
- If not amisingle then exit sub 'or wscript. Quit
- 'Do what's your want to do .....
- '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.
- 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 ', which is more realistic than fileexists .....
- Wscript. Sleep 1000 'detected every 1 second
- Loop
- Msgbox "size overflow ."
- End sub
- 'Does the script only exist for a single instance?
- '[Out] Boolean amisingle: returns true if only one script is run; otherwise, false
- Function amisingle ()
- Dim ob1_mi, objprocs, objproc
- Dim intcount: intcount = 0' Number of running instances
- 'Retrieve the WMI Service. Note that this is GetObject.
- Set ob1_mi = GetObject ("winmgmts: //./root/cimv2 ")
- 'Query a process named "wscript. Shell"
- Set objprocs1_ob1_mi.exe cquery ("select * From win32_process where name1_'wscript.exe '")
- Comparing the running parameters of wscript.exe, if the parameters are the same as those of the script
- For each objproc in objprocs
- If instr (objproc. CommandLine, wscript. scriptfullname)> 0 then intcount = intcount + 1
- Next
- Amisingle = (intcount = 1)
- End Function