<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; VBS/WMI: Ограничение времени работы избранных процессов]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=4391&amp;type=atom" />
	<updated>2010-10-23T13:25:07Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=4391</id>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40764#p40764" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>smaharbA пишет:</cite><blockquote><p>а о временных и постоянных подписчиков никто не в курсе что ли ?</p></blockquote></div><p><a href="http://www.samag.ru/art/03.2006/03.2006_05.html">Почитал</a> про подписчиков, Вы считаете с ними легче ?<br />Это на каждом компе у пользователя что-то компилить надо будет...&nbsp; и какой тогда алгоритм учёта будет ?<br />Не подумайте что я придираюсь...&nbsp; я просто хочу разобраться в их применении и употреблении относительно данной задачи...</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-10-23T13:25:07Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40764#p40764</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40762#p40762" />
			<content type="html"><![CDATA[<p>Спасибо !!!</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-10-23T12:53:04Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40762#p40762</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40752#p40752" />
			<content type="html"><![CDATA[<p><strong>Евген</strong><br />Спасибо, твой статус изменён. Прошу <a href="http://forum.script-coding.com/rules.html#6.">ознакомиться</a> и создать новую тему в Коллекции.<br /><span class="postimg"><img src="http://yoursmileys.ru/tsmile/forum/t1230.gif" alt="http://yoursmileys.ru/tsmile/forum/t1230.gif" /></span></p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2010-10-23T09:52:25Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40752#p40752</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40747#p40747" />
			<content type="html"><![CDATA[<p>Я - нет...<br />если можете, дайте ссылку или опишите...</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-10-23T06:45:03Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40747#p40747</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40746#p40746" />
			<content type="html"><![CDATA[<p>а о временных и постоянных подписчиков никто не в курсе что ли ?</p>]]></content>
			<author>
				<name><![CDATA[smaharbA]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=2911</uri>
			</author>
			<updated>2010-10-23T06:15:55Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40746#p40746</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=40738#p40738" />
			<content type="html"><![CDATA[<p>Коллеги, занесите этот скрипт пожалуйста в коллекцию...<br />я его уже скольким своим друзьям раздал <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /> причём по их же просьбе...&nbsp; &nbsp;они все ищуют какой-нить софтвер на данную тему, а тут на - готовое решение с полным логированием...&nbsp; </p><p>Решение не из простых...&nbsp; &nbsp;тут подумать и придумать надо было...</p><p>Администрация, Вы не против ?</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-10-22T14:34:22Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=40738#p40738</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35942#p35942" />
			<content type="html"><![CDATA[<p>OFF: Сегодня вместо детей жена наткнулась на результат действия скрипта <img src="//forum.script-coding.com/img/smilies/hmm.png" width="15" height="15" /><br />возвращаюсь с вечерней пробежки, все провода из розеток выдернуты, ADSL модем выключен, клава и мышь выдернуты из системного блока, стабилизатор вырублен, жена сидит в другой комнате зырит телек (от жены только изображение, звука нет, на пинги нет ответа). Когда выходил на пробежку - сидела, шпилила...</p><p>Фиговая наверно затея скрипта <img src="//forum.script-coding.com/img/smilies/sad.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-20T15:46:49Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35942#p35942</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35854#p35854" />
			<content type="html"><![CDATA[<p>До полного фарша ещё сделал не плохое логирование, логирует следующее:<br />1) Время запуска любого процесса из списка<br />2) Время его нормального закрытия<br />3) Время принудительного закрытия<br />4) Время предотвращение запуска<br />5) Смену суток</p><p>Файл лога располагается в папке где скрипт.</p><div class="codebox"><pre><code>Public strPrevent       &#039; флаг запрета запуска
Public arrProcesses     &#039; массив процессов
Public LogFile
Const ForAppending = 8
Const HKEY_CURRENT_USER = &amp;H80000001
strPause=3000           &#039; значение паузы 3 секунды
strPauseTime=&quot;00:00:03&quot; &#039; тоже самое в формате времени
TimeLimit=&quot;00:45:00&quot;    &#039; ограничение шпильного времени 45 минут 
strKeyPath = &quot;Software\proc_monitor&quot;                          &#039; ветка реестра где будет производиться учёт
Set FileSytemObject = CreateObject(&quot;Scripting.FileSystemObject&quot;) 
ParentFolderName = FileSytemObject.GetParentFolderName(Wscript.ScriptFullName) 
LogFile = FileSytemObject.BuildPath(ParentFolderName,&quot;PlayTime.log&quot;) 

arrProcesses=Array(&quot;IceAge2pc.exe&quot;,&quot;dirt2.exe&quot;,&quot;DiRT.exe&quot;,&quot;speed.exe&quot;,&quot;Game.exe&quot;,&quot;iceage3.exe&quot;,&quot;Tumblebugs.exe&quot;,&quot;FarmFrenzy3_America.wrp.exe&quot;,&quot;FerrariVR.exe&quot;,&quot;MTX.exe&quot;,&quot;FarmFrenzy3.wrp.exe&quot;,&quot;motogp2.exe&quot;,&quot;TmForever.exe&quot;,&quot;FarmFrenzy3_Arctica.exe&quot;)

strComputer = &quot;.&quot;
Set oReg=GetObject(&quot;winmgmts:{impersonationLevel=impersonate}!\\&quot; &amp; strComputer &amp; &quot;\root\default:StdRegProv&quot;)
Set objWMIService = GetObject(&quot;winmgmts:\\&quot; &amp; strComputer &amp; &quot;\root\CIMV2&quot;) 
Set WshShell = CreateObject(&quot;WScript.Shell&quot;)

On Error Resume Next                                         &#039; включаем обработку ошибок
WshShell.RegRead &quot;HKEY_CURRENT_USER\Software\proc_monitor\&quot;  &#039; проверяем, есть ли такая ветка реестра
If Err.Number&lt;&gt;0 Then
Err.Clear
On Error Goto 0                                               &#039; отключаем обработку ошибок
oReg.CreateKey HKEY_CURRENT_USER,strKeyPath                   &#039; если нет - то создаём ветку
oReg.CreateKey HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;     &#039; создаём веточку для даты
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,CStr(DateValue(Date)) &#039; прописываем сегоднящнюю дату
End If



      &#039; сейчас будем синхронизировать список процессов в скрипте и реестре

strValue = &quot;00:00:00&quot;  &#039; нулевое время
oReg.EnumValues HKEY_CURRENT_USER, strKeyPath,arrValueNames

If IsNull(arrValueNames) Then               &#039; в реестре всё пусто, надо заполнять списком

For Each Process in arrProcesses
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strValue
Next

Else                                        &#039; если учёт ранее вёлся


  &#039; Синхронизация реестра к массиву
  &#039; лишнее из реестра удаляется

For r=0 to UBound(arrValueNames)
strFlag=0                            &#039; флаг совпадения наименования процесса
For n=0 to UBound(arrProcesses)
If arrValueNames(r)=arrProcesses(n) Then
strFlag=1
Exit For
End If
Next

If strFlag=0 Then                     &#039; если совпадения нет - то удаляем
oReg.DeleteValue HKEY_CURRENT_USER,strKeyPath,arrValueNames(r)
End If

Next


  &#039; Синхронизация массива к реестру
  &#039; недостающие процессы дописываются в реестр

For r=0 to UBound(arrProcesses)
strFlag=0                            &#039; флаг совпадения наименования процесса
For n=0 to UBound(arrValueNames)
If arrProcesses(r)=arrValueNames(n) Then
strFlag=1
Exit For
End If
Next

If strFlag=0 Then             &#039; если совпадения нет - то дописываем в реестр
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,arrProcesses(r),strValue
End If

Next

End if



                               &#039;   ОСНОВНОЙ ЦИКЛ

&#039; асинхронный обработчик на создание процесса
Set SINKC = WScript.CreateObject(&quot;WbemScripting.SWbemSink&quot;,&quot;SINKC_&quot;)
objWMIService.ExecNotificationQueryAsync SINKC, &quot;SELECT * FROM __InstanceCreationEvent WITHIN 3 WHERE TargetInstance ISA &#039;Win32_Process&#039;&quot;

&#039; асинхронный обработчик на удаление процесса
Set SINKT = WScript.CreateObject(&quot;WbemScripting.SWbemSink&quot;,&quot;SINKT_&quot;)
objWMIService.ExecNotificationQueryAsync SINKT, &quot;SELECT * FROM __InstanceDeletionEvent WITHIN 3 WHERE TargetInstance ISA &#039;Win32_Process&#039;&quot;

Do While 1=1

&#039;   I  считывание, сравнение даты, обнуление счётчиков при смене даты

oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,strDate  &#039; считываем дату последнего учёта

If DateValue(strDate)&lt;&gt;DateValue(Date) Then                                       &#039; если даты не совпадают
For Each Process in arrProcesses
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strValue                 &#039; то обнуляем счётчики отработанного времени у всех процессов
Next
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,CStr(DateValue(Date)) &#039; прописываем сегоднящнюю дату
   &#039; логируем смену даты
   Set LogF = FileSytemObject.OpenTextFile(LogFile, ForAppending, True) 
   LogF.WriteLine String(25,&quot;-&quot;) &amp; &quot;  &quot; &amp; DateValue(Date) &amp; &quot;  &quot; &amp; String(25,&quot;-&quot;)
   LogF.Close
End If

&#039;  II  расчёт суммарного шпильного времени

sumTime=&quot;00:00:00&quot;

For Each Process in arrProcesses
oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strTime
sumTime=TimeValue(sumTime) + TimeValue(strTime)
Next

&#039;  III  сравниваем &quot;выработанное&quot; время с лимитным и устанавливаем флаг запрета шпиля

If TimeValue(sumTime)&gt;=TimeValue(TimeLimit) Then
strPrevent=1                                       &#039; ЗАПРЕЩЕНО
Else
strPrevent=0                                       &#039; РАЗРЕШЕНО
End If

&#039;  IV   учёт времени работы процессов из списка и убивание процессов при выставленном флаге

Set colItems = objWMIService.ExecQuery(&quot;SELECT * FROM Win32_Process&quot;) 
For Each objItem in colItems 
strOut=0           &#039; обнуление флага выхода из цклов в начале первичного цикла For
   For Each Process in arrProcesses
     If LCase(objItem.Name)=LCase(Process) Then                                                                  &#039; если процесс из списка работает
              &#039; если флаг запрета запуска выставлен - то убиваем процессы из списка
       If strPrevent=1 Then  
           objItem.Terminate
      &#039; здесь логируем здесь логируем принудительно закрытый процесс
   Set LogF = FileSytemObject.OpenTextFile(LogFile, ForAppending, True) 
   LogF.WriteLine Now &amp; &quot; принудительно закрыт процесс: &quot; &amp; LCase(Process)
   LogF.Close
           Exit For
       Else
          oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strTime
          oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,CStr(TimeValue(strTime)+TimeValue(strPauseTime))    &#039; то к его времени прибавляем время паузы
           strOut=1   &#039; флаг выхода из цикла вложенного For при встрече любого первого процесса
           Exit For
       End If
     End If
   Next
If strOut=1 Then   &#039; в соответствии с флагом выхода выходим из первичного цикла For
     Exit For
End If
Next

Wscript.Sleep strPause
Loop


      &#039;  асинхронный убийца при запуске

Sub SINKC_OnObjectReady(objLatestEvent, objAsyncContext)  

   For Each Process in arrProcesses
   If LCase(Process)=LCase(objLatestEvent.TargetInstance.Name) Then

   If strPrevent=1 Then    &#039; при запуске убиваем процессы из списка при запрещающем флаге
   objLatestEvent.TargetInstance.Terminate

   &#039; здесь логируем предотвращённый запуск
   Set LogF = FileSytemObject.OpenTextFile(LogFile, ForAppending, True) 
   LogF.WriteLine Now &amp; &quot; предотвращен запуск: &quot; &amp; objLatestEvent.TargetInstance.Name
   LogF.Close
   Exit Sub
   End If

   &#039; здесь логируем разрешённый запуск
   Set LogF = FileSytemObject.OpenTextFile(LogFile, ForAppending, True) 
   LogF.WriteLine Now &amp; &quot; запущен процесс: &quot; &amp; objLatestEvent.TargetInstance.Name
   LogF.Close

   End If
   Next

End Sub



&#039; логирование при закрытии процесса

Sub SINKT_OnObjectReady(objLatestEvent, objAsyncContext)  

   For Each Process in arrProcesses
   If LCase(Process)=LCase(objLatestEvent.TargetInstance.Name) Then
   If strPrevent&lt;&gt;1 Then  &#039; если этот флаг не учитывать - то будет проходить двойное логирование (принудительное и потом нормальное)
   Set LogF = FileSytemObject.OpenTextFile(LogFile, ForAppending, True) 
   LogF.WriteLine Now &amp; &quot; нормально закрыт процесс: &quot; &amp; objLatestEvent.TargetInstance.Name
   LogF.Close
   End If
   End If
   Next

End Sub</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-17T13:20:42Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35854#p35854</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35828#p35828" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Евген пишет:</cite><blockquote><p>Теперь можно и в коллекцию <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" /></p></blockquote></div><p>Если администрация считает анолагично(?) - могу добавить, я только за... <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Lucky]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25698</uri>
			</author>
			<updated>2010-05-16T06:38:19Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35828#p35828</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35821#p35821" />
			<content type="html"><![CDATA[<p>Спасибо ! <img src="//forum.script-coding.com/img/smilies/big_smile.png" width="15" height="15" /><br />Рад что не мне одному это пригодилось !!!<br />Теперь можно и в коллекцию <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-15T10:20:41Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35821#p35821</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35820#p35820" />
			<content type="html"><![CDATA[<p><strong>Евген</strong>, поздравляю вас, теперь отлично получилось! <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Lucky]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25698</uri>
			</author>
			<updated>2010-05-15T08:56:19Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35820#p35820</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35818#p35818" />
			<content type="html"><![CDATA[<div class="codebox"><pre><code>Public strPrevent       &#039; флаг запрета запуска
Public arrProcesses     &#039; массив процессов
Const HKEY_CURRENT_USER = &amp;H80000001
strPause=3000           &#039; значение паузы 3 секунды
strPauseTime=&quot;00:00:03&quot; &#039; тоже самое в формате времени
TimeLimit=&quot;00:45:00&quot;    &#039; ограничение шпильного времени 45 минут 
strKeyPath = &quot;Software\proc_monitor&quot;                          &#039; ветка реестра где будет производиться учёт
arrProcesses=Array(&quot;monitor.exe&quot;,&quot;excel.exe&quot;,&quot;winword.exe&quot;)   &#039; список ограничиваемых процессов


strComputer = &quot;.&quot;
Set oReg=GetObject(&quot;winmgmts:{impersonationLevel=impersonate}!\\&quot; &amp; strComputer &amp; &quot;\root\default:StdRegProv&quot;)
Set objWMIService = GetObject(&quot;winmgmts:\\&quot; &amp; strComputer &amp; &quot;\root\CIMV2&quot;) 
Set WshShell = CreateObject(&quot;WScript.Shell&quot;)

On Error Resume Next                                         &#039; включаем обработку ошибок
WshShell.RegRead &quot;HKEY_CURRENT_USER\Software\proc_monitor\&quot;  &#039; проверяем, есть ли такая ветка реестра
If Err.Number&lt;&gt;0 Then
Err.Clear
On Error Goto 0                                               &#039; отключаем обработку ошибок
oReg.CreateKey HKEY_CURRENT_USER,strKeyPath                   &#039; если нет - то создаём ветку
oReg.CreateKey HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;     &#039; создаём веточку для даты
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,CStr(DateValue(Date)) &#039; прописываем сегоднящнюю дату
End If



      &#039; сейчас будем синхронизировать список процессов в скрипте и реестре

strValue = &quot;00:00:00&quot;  &#039; нулевое время
oReg.EnumValues HKEY_CURRENT_USER, strKeyPath,arrValueNames

If IsNull(arrValueNames) Then               &#039; в реестре всё пусто, надо заполнять списком

For Each Process in arrProcesses
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strValue
Next

Else                                        &#039; если учёт ранее вёлся


  &#039; Синхронизация реестра к массиву
  &#039; лишнее из реестра удаляется

For r=0 to UBound(arrValueNames)
strFlag=0                            &#039; флаг совпадения наименования процесса
For n=0 to UBound(arrProcesses)
If arrValueNames(r)=arrProcesses(n) Then
strFlag=1
Exit For
End If
Next

If strFlag=0 Then                     &#039; если совпадения нет - то удаляем
oReg.DeleteValue HKEY_CURRENT_USER,strKeyPath,arrValueNames(r)
End If

Next


  &#039; Синхронизация массива к реестру
  &#039; недостающие процессы дописываются в реестр

For r=0 to UBound(arrProcesses)
strFlag=0                            &#039; флаг совпадения наименования процесса
For n=0 to UBound(arrValueNames)
If arrProcesses(r)=arrValueNames(n) Then
strFlag=1
Exit For
End If
Next

If strFlag=0 Then             &#039; если совпадения нет - то дописываем в реестр
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,arrProcesses(r),strValue
End If

Next

End if



                               &#039;   ОСНОВНОЙ ЦИКЛ

Set SINK = WScript.CreateObject(&quot;WbemScripting.SWbemSink&quot;,&quot;SINK_&quot;)
objWMIService.ExecNotificationQueryAsync SINK, &quot;SELECT * FROM __InstanceCreationEvent WITHIN 3 WHERE TargetInstance ISA &#039;Win32_Process&#039;&quot;

Do While 1=1

&#039;   I  считывание, сравнение даты, обнуление счётчиков при смене даты

oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,strDate  &#039; считываем дату последнего учёта

If DateValue(strDate)&lt;&gt;DateValue(Date) Then                                       &#039; если даты не совпадают
For Each Process in arrProcesses
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strValue                 &#039; то обнуляем счётчики отработанного времени у всех процессов
Next
oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath &amp; &quot;\CurrDate&quot;,&quot;strDate&quot;,CStr(DateValue(Date)) &#039; прописываем сегоднящнюю дату
End If

&#039;  II  расчёт суммарного шпильного времени

sumTime=&quot;00:00:00&quot;

For Each Process in arrProcesses
oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strTime
sumTime=TimeValue(sumTime) + TimeValue(strTime)
Next

&#039;  III  сравниваем &quot;выработанное&quot; время с лимитным и устанавливаем флаг запрета шпиля

If TimeValue(sumTime)&gt;=TimeValue(TimeLimit) Then
strPrevent=1                                       &#039; ЗАПРЕЩЕНО
Else
strPrevent=0                                       &#039; РАЗРЕШЕНО
End If

&#039;  IV   учёт времени работы процессов из списка и убивание процессов при выставленном флаге

Set colItems = objWMIService.ExecQuery(&quot;SELECT * FROM Win32_Process&quot;) 
For Each objItem in colItems 
strOut=0           &#039; обнуление флага выхода из циклов в начале первичного цикла For
   For Each Process in arrProcesses
     If LCase(objItem.Name)=LCase(Process) Then                                                                  &#039; если процесс из списка работает
              &#039; если флаг запрета запуска выставлен - то убиваем процессы из списка
       If strPrevent=1 Then  
           objItem.Terminate
           Exit For
       Else
          oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath,Process,strTime
          oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,Process,CStr(TimeValue(strTime)+TimeValue(strPauseTime))    &#039; то к его времени прибавляем время паузы
           strOut=1   &#039; флаг выхода из цикла вложенного For при встрече любого первого процесса
           Exit For
       End If
     End If
   Next
If strOut=1 Then   &#039; в соответствии с флагом выхода выходим из первичного цикла For
     Exit For
End If
Next

Wscript.Sleep strPause
Loop


      &#039;  асинхронный убийца при запуске

Sub SINK_OnObjectReady(objLatestEvent, objAsyncContext)  

   If strPrevent=1 Then    &#039; при запуске убиваем процессы из списка при запрещающем флаге

   For Each Process in arrProcesses
   If LCase(Process)=LCase(objLatestEvent.TargetInstance.Name) Then
   objLatestEvent.TargetInstance.Terminate
   End If
   Next

   End if

End Sub</code></pre></div><p>Исправил, сейчас будет учитываться любой один первый встретившийся процесс</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-15T04:36:27Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35818#p35818</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35817#p35817" />
			<content type="html"><![CDATA[<p>Согласен <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br />думаю Ваше предложение правильное... <br />сделаю...</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-15T03:59:36Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35817#p35817</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35805#p35805" />
			<content type="html"><![CDATA[<p>Конечно, это почти риторический вопрос. <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br /></p><div class="quotebox"><cite>Евген пишет:</cite><blockquote><p>ну и WQL в WMI не поддерживает оператор ни DISTINCT ни GROUP BY чтобы отобрать только уникальные имена процессов</p></blockquote></div><p>А что если при сканировании запущенных процессов чуть изменить способ: методом перебора при первом же результате (найден любой искомый процесс из массива) принимать меры (добавлять 3 сек и повторить скан через 3 сек, и так далее как у вас в примере...)?</p>]]></content>
			<author>
				<name><![CDATA[Lucky]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25698</uri>
			</author>
			<updated>2010-05-14T16:48:08Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35805#p35805</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS/WMI: Ограничение времени работы избранных процессов]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=35804#p35804" />
			<content type="html"><![CDATA[<p>Можно я не буду отвечать... <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br />мне всё понятно...;)</p>]]></content>
			<author>
				<name><![CDATA[Евген]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=25253</uri>
			</author>
			<updated>2010-05-14T16:37:43Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=35804#p35804</id>
		</entry>
</feed>
