<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; VBS: Удаление комментариев]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=6097&amp;type=atom" />
	<updated>2012-09-29T21:11:57Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=6097</id>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=64377#p64377" />
			<content type="html"><![CDATA[<p>Спасибо, <strong>Rumata</strong>. Напомнил тему. <br />Написал <a href="http://da440dil.narod.ru/vbshaker.html">сервис</a> по мотивам задачи. Если есть желание можно на script-coding страничку разместить. Замечания принимаются.<br />HTA:<br /></p><div class="codebox"><pre><code>
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;VBShaker - VBScript code obfuscation&lt;/title&gt;
	&lt;meta http-equiv=content-type content=&quot;text-html; charset=windows-1251&quot;&gt;
    &lt;meta http-equiv=MSThemeCompatible content=yes&gt;
    &lt;hta:application              
		icon=wscript.exe
        scroll=no
		windowstate=maximize
		version=&quot;1.0&quot;
    &gt;
&lt;/head&gt;
&lt;style type=&quot;text/css&quot;&gt;
	textarea {width:49%; height:93%; font: normal 12px sans-serif}
	#scr1 {float:left;}
	#scr2 {float:right;}
	#btn,#btn1 {position:relative; font: bold 12px sans-serif; width:100px; height:25px; cursor:hand;}
	#btn {float:left; margin:0px 3px 3px 0px;}
	#btn1 {float:right; margin:0px 0px 3px 3px;}
	#tip {display:none; position:absolute; background:#fff; top:3px;left:110px; color:#000; padding:3px; font: bold italic 12px sans-serif;	filter:alpha(opacity=80);}
	#clr {clear:both;}
	#chk{float:left; position:relative;font: bold italic 12px sans-serif;}
	input {vertical-align:middle; margin:4px;}
	#min1,#max1,#proc1,#proc2 {height:18px; width:25px; font: bold 12px sans-serif;}
	#cr {font: bold italic 12px sans-serif; text-align: center;}
	
&lt;/style&gt;

&lt;script language=&quot;JavaScript&quot;&gt;	
	function mainFunction() {
		var arrLines;		
		if (document.all){
			arrLines = scr1.value.split(&quot;\r\n&quot;);
		}
		else {
			arrLines = scr1.value.split(&quot;\n&quot;);
		}
		var ret = validateValues();
		if (ret != &quot;&quot;) {
			alert(ret);
			return;
		}		
		if (chk1.checked) {
			removeComments(arrLines);
		}		
		if (chk2.checked) {
			var nameArr = getVarName(arrLines);
			if (log1.checked) {
				var log = open(&quot;&quot;,&quot;&quot;,&quot;height=400,width=600&quot;);
				if (log != null) {
					var logHTML = &quot;&quot;
					for(var i=0; i&lt;nameArr.length; i++) {			
						logHTML += nameArr[i][0] + &quot; = &quot; + nameArr[i][1] + &quot;&lt;br/&gt;&quot;;				
					}				
					log.document.write(logHTML);
					log.focus();
				}
			}
		}
		scr2.value = &quot;&quot;;		
		scr2.value = arrLines.join(&quot;\n&quot;);		
	}	
	function validateValues() {	
		var ret = &quot;&quot;;		
		var temp = parseInt(min1.value);
		if (min1.value.search(/\D/)!=-1 || temp &lt; 2 || temp &gt; 255) {
			ret += &quot;min char should be an integer between 2 and 255 \n&quot;;
		}
		temp = parseInt(max1.value);
		if (max1.value.search(/\D/)!=-1 || temp &lt; 2 || temp &gt; 255) {
			ret += &quot;max char should be an integer between 2 and 255 \n&quot;;
		}
		temp = parseInt(proc1.value);
		if (proc1.value.search(/\D/)!=-1 || temp &lt; 0 || temp &gt; 100) {
			ret += &quot;% letters should be an integer between 0 and 100 \n&quot;;
		}
		temp = parseInt(proc2.value);
		if (proc2.value.search(/\D/)!=-1  || temp &lt; 0 || temp &gt; 100) {
			ret += &quot;% upper case should be an integer between 0 and 100 \n&quot;;
		}		
		return ret;
	}
	function getVarName(arrLines) {
		var nameArr = [];
		for(var i=0; i&lt;arrLines.length; i++) {			
			if (arrLines[i].search(/\b(?:dim|const|sub|function|public|private|class|property)\b[^(?:\&quot;|_$)]/i)!=-1 &amp;&amp; 
				arrLines[i].search(/\b(?:end|class_initialize|class_terminate)\b/i)==-1) {				
				var temp = arrLines[i].replace(/\b(?:dim|const|public|private|sub|function|class|property|get|let|set)\b|\(|\)|,|\d|=.*?(?:,|&#039;.*$|\brem\b.*$|$)/gi,&quot; &quot;)
					.replace(/^\s+|\s+$/g,&quot;&quot;).split(/\s+/);				
				for(var j=0; j&lt;temp.length; j++) {					
					var nameFound = false;
						for(var k=0; k&lt;nameArr.length; k++) {
							if(temp[j] == nameArr[k][0]) {
								nameFound = true;
								break;
							}
						}
					if(!nameFound) {						
						var newnameFound = true;
						while(newnameFound) {
							var tempName = getRandomName();
							for(var k=0; k&lt;nameArr.length; k++) {
								if (tempName == nameArr[k][1]) {									
									break;
								}
							}
							if (checkRandomName(tempName)) {
								newnameFound = false;
							}
						}						
						nameArr.push([temp[j],tempName,new RegExp(&#039;\\b&#039;+temp[j]+&#039;\\b(?!&quot;)&#039;,&#039;g&#039;)]);											
					}
				}							
			}			
		}
		for(var i=0; i&lt;arrLines.length; i++) {			
			for(var j=0; j&lt;nameArr.length; j++) {
				arrLines[i] = arrLines[i].replace(nameArr[j][2],nameArr[j][1]);
			}
		}
		return nameArr;
	}
	function getRandomName() {
		var max = parseInt(max1.value);
		var min = parseInt(min1.value);
		var proc = parseInt(proc1.value);
		var procU = parseInt(proc2.value);
		var charArray = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;,&quot;_&quot;]		
		if (Math.random() &lt; procU/100) {
			var retArr = [charArray[Math.floor(Math.random() * 26)].toUpperCase()];
		}
		else {
			var retArr = [charArray[Math.floor(Math.random() * 26)]];
		}
		var varLen = Math.floor(Math.random() * (max - min + 1)) + min;		
		for (i=1; i&lt;varLen; i++) {
			if (Math.random() &lt; proc/100) {
				if (Math.random() &lt; procU/100) {
					retArr.push(charArray[Math.floor(Math.random() * 27)].toUpperCase());					
				}
				else {					
					retArr.push(charArray[Math.floor(Math.random() * 27)]);
				}				
			}
			else {
				retArr.push(Math.floor(Math.random() * 10));
			}
		}
		return retArr.join(&quot;&quot;);
	}
	function checkRandomName(name) {		
		if (name.substring(0,1) == &quot;vb&quot;) {
			return false;
		}		
		var arr = [&quot;dim&quot;,&quot;const&quot;,&quot;public&quot;,&quot;private&quot;,&quot;sub&quot;,&quot;function&quot;,&quot;class&quot;,&quot;property&quot;,&quot;get&quot;,&quot;let&quot;,&quot;set&quot;,&quot;class_initialize&quot;,&quot;class_terminate&quot;,
			&quot;if&quot;,&quot;or&quot;,&quot;and&quot;,&quot;not&quot;,&quot;then&quot;,&quot;else&quot;,&quot;elseif&quot;,&quot;end&quot;,&quot;for&quot;,&quot;each&quot;,&quot;in&quot;,&quot;to&quot;,&quot;step&quot;,&quot;next&quot;,&quot;do&quot;,&quot;while&quot;,&quot;loop&quot;,&quot;until&quot;,&quot;wend&quot;,&quot;select&quot;,&quot;case&quot;,&quot;exit&quot;,&quot;with&quot;,
			&quot;xor&quot;,&quot;err&quot;,&quot;call&quot;,&quot;on&quot;,&quot;error&quot;,&quot;resume&quot;,&quot;goto&quot;,&quot;redim&quot;,&quot;preserve&quot;,&quot;me&quot;,&quot;mod&quot;,&quot;rem&quot;,&quot;new&quot;,&quot;true&quot;,&quot;false&quot;,&quot;option&quot;,&quot;explicit&quot;,
			&quot;date&quot;,&quot;dateadd&quot;,&quot;datediff&quot;,&quot;datepart&quot;,&quot;dateserial&quot;,&quot;datevalue&quot;,&quot;day&quot;,&quot;formatdatetime&quot;,&quot;hour&quot;,&quot;isdate&quot;,&quot;minute&quot;,&quot;month&quot;,&quot;monthname&quot;,
			&quot;now&quot;,&quot;second&quot;,&quot;time&quot;,&quot;timer&quot;,&quot;timeserial&quot;,&quot;timevalue&quot;,&quot;weekday&quot;,&quot;weekdayname&quot;,&quot;year&quot;,
			&quot;asc&quot;,&quot;cbool&quot;,&quot;cbyte&quot;,&quot;ccur&quot;,&quot;cdate&quot;,&quot;cdbl&quot;,&quot;chr&quot;,&quot;cint&quot;,&quot;clng&quot;,&quot;csng&quot;,&quot;cstr&quot;,&quot;hex&quot;,&quot;oct&quot;,
			&quot;formatcurrency&quot;,&quot;formatdatetime&quot;,&quot;formatnumber&quot;,&quot;formatpercent&quot;,
			&quot;abs&quot;,&quot;atn&quot;,&quot;cos&quot;,&quot;exp&quot;,&quot;int&quot;,&quot;fix&quot;,&quot;log&quot;,&quot;oct&quot;,&quot;rnd&quot;,&quot;sgn&quot;,&quot;sin&quot;,&quot;sqr&quot;,&quot;tan&quot;,
			&quot;array&quot;,&quot;filter&quot;,&quot;isarray&quot;,&quot;join&quot;,&quot;lbound&quot;,&quot;split&quot;,&quot;ubound&quot;,
			&quot;instr&quot;,&quot;instrrev&quot;,&quot;lcase&quot;,&quot;left&quot;,&quot;len&quot;,&quot;ltrim&quot;,&quot;rtrim&quot;,&quot;trim&quot;,&quot;mid&quot;,&quot;replace&quot;,&quot;right&quot;,&quot;space&quot;,&quot;strcomp&quot;,&quot;string&quot;,&quot;strreverse&quot;,&quot;ucase&quot;,
			&quot;createobject&quot;,&quot;eval&quot;,&quot;getlocale&quot;,&quot;getobject&quot;,&quot;getref&quot;,&quot;inputbox&quot;,&quot;isempty&quot;,&quot;isnull&quot;,&quot;isnumeric&quot;,&quot;isobject&quot;,&quot;loadpicture&quot;,&quot;msgbox&quot;,
			&quot;rgb&quot;,&quot;round&quot;,&quot;scriptengine&quot;,&quot;scriptenginebuildversion&quot;,&quot;scriptenginemajorversion&quot;,&quot;scriptengineminorversion&quot;,&quot;setlocale&quot;,&quot;typename&quot;,&quot;vartype&quot;];					
		for(var i=0; i&lt;arr.length; i++) {
			if(name == arr[i]) {
				return false;
			}
		}		
		return true;
	}
	function removeComments(arrLines) {		
		for(var i=0; i&lt;arrLines.length; i++) {						
			arrLines[i] = arrLines[i].replace(/^\s+|^\s*(?:&#039;|\brem\b).*$|(?:&#039;|\brem\b)[^(?:\&quot;|_$)].*$|\s+$/gi,&quot;&quot;);						
			if (arrLines[i].search(/^\s*$/)!=-1) {
				arrLines.splice(i,1);
				i--;				
			}
		}	
	}	
	function clearFunction() {
		scr1.value = &quot;&quot;;
		scr2.value = &quot;&quot;;
		min1.value = &quot;2&quot;;
		max1.value = &quot;10&quot;;
		proc1.value = &quot;60&quot;;
		proc2.value = &quot;40&quot;;
		log1.checked = false;
	}
&lt;/script&gt;

&lt;body&gt;
	&lt;button id=&quot;btn&quot; onclick=&quot;mainFunction()&quot; onmouseover=&quot;tip.style.display = &#039;block&#039;&quot; onmouseout=&quot;tip.style.display = &#039;none&#039;&quot;&gt;S H A K E &amp;nbsp;&amp;nbsp;I T&lt;/button&gt;	
	&lt;div id=&quot;chk&quot;&gt;
		&lt;input id=&quot;chk1&quot; type=&quot;checkbox&quot; checked=&quot;checked&quot; /&gt;remove comments
		&lt;input id=&quot;chk2&quot; type=&quot;checkbox&quot; checked=&quot;checked&quot; /&gt;rename explicitly declared variables
		&lt;input id=&quot;min1&quot; type=&quot;text&quot; value=&quot;2&quot; /&gt;min char
		&lt;input id=&quot;max1&quot; type=&quot;text&quot; value=&quot;10&quot; /&gt;max char
		&lt;input id=&quot;proc1&quot; type=&quot;text&quot; value=&quot;60&quot; /&gt;% letters
		&lt;input id=&quot;proc2&quot; type=&quot;text&quot; value=&quot;40&quot; /&gt;% upper case
		&lt;input id=&quot;log1&quot; type=&quot;checkbox&quot; /&gt;log
	&lt;/div&gt;
	&lt;button id=&quot;btn1&quot; onclick=&quot;clearFunction()&quot;&gt;C L E A R&lt;/button&gt;
	&lt;span id=&quot;tip&quot;&gt;don&#039;t break it, took me time to make it&lt;/span&gt;
	&lt;div id=&quot;clr&quot;&gt;&lt;/div&gt;
	&lt;textarea id=&quot;scr1&quot;&gt;&lt;/textarea&gt;
	&lt;textarea id=&quot;scr2&quot;&gt;&lt;/textarea&gt;
	&lt;div id=&quot;cr&quot;&gt;Copyright © by  &lt;a href=&quot;http://www.daspot.ru&quot;&gt;Anatoly Demidovich&lt;/a&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></div>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2012-09-29T21:11:57Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=64377#p64377</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=64063#p64063" />
			<content type="html"><![CDATA[<p>Случайно попалось на глаза. Программа, судя по названию, делает обратную задачу - структурирует и форматирует текст: <a href="http://demon.tw/my-work/vbs-beautifier.html">VbsBeautifier</a>. Сам не проверял, понравилась задумка.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2012-09-21T07:57:18Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=64063#p64063</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50845#p50845" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Vladimir пишет:</cite><blockquote><p>Можно доделать обфускацию с заменой имён переменных на графически схожие символы.</p></blockquote></div><p>ОК, растолкуйте каким образом - доделаем.</p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-23T18:49:50Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50845#p50845</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50838#p50838" />
			<content type="html"><![CDATA[<p>Попалась история по теме <a href="http://ithappens.ru/story/7064">&quot;Заблудиться в трёх килососнах&quot;</a>.<br />Можно доделать обфускацию с заменой имён переменных на графически схожие символы.</p>]]></content>
			<author>
				<name><![CDATA[Vladimir]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27154</uri>
			</author>
			<updated>2011-08-23T17:03:01Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50838#p50838</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50779#p50779" />
			<content type="html"><![CDATA[<p>Меня немного смущает увеличение кода. В любом случае профи сразу разгадает в чем подвох, если код целиком шифрован. Уж лучше остановиться на VBS.Encode. Можно долго обсуждать об алгоритмах обфускации, о том как один код может формировать другой, использовании мусорных конструкций и тому подобное. Мне больше в последнее время нравится использование фишки как социальная инженерия. Я имею в виду, что биты кода можно представить в виде пробела (1) и табуляции (0) и прятать его в <a href="http://forum.script-coding.com/viewtopic.php?id=4328">комментариях</a>. Пробельные символы могут сбить с толку даже спеца. Правда увеличение шифрованной части в 8 раз, но тем не менее, так можно скрыть парольную информацию.</p>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2011-08-21T19:00:16Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50779#p50779</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50772#p50772" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>JSman пишет:</cite><blockquote><p>Меняем Execute на WScript.Echo и получаем исходный код.</p></blockquote></div><p>Не совсем исходный. Считаете фичу с трансформацией символов лишней?</p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-21T16:35:48Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50772#p50772</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50770#p50770" />
			<content type="html"><![CDATA[<p>Меняем Execute на WScript.Echo и получаем исходный код.</p>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2011-08-21T15:45:30Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50770#p50770</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50760#p50760" />
			<content type="html"><![CDATA[<p>Добавил новую фичу - трансформацию символов. <br />Делает код еще более нечитабельным, но значительно увеличивает размер файла. <br />Выложил <a href="http://narod.ru/disk/22325477001/VBShaker.zip.html">оба варианта скрипта</a> - с кодом до трансформации и после.<br /></p><div class="codebox"><pre><code>Option Explicit
    On Error Resume Next
    Const strNewNamePref = &quot;New&quot; &#039;префикс нового имени файла    
    Const intMaxLen = 11 &#039;максимальная длина имени в символах (Const-1)
    Const intPro = 60 &#039;процент символов алфавита в новом рандомизированном имени    
    Const bStir = True &#039; необходимость взбалтывания имен переменных, False - не взбалтываем :)
    Const bWriteLog = False &#039;необходимость создания файла журнала переименования, False - не создаем
    Const bTransChr = False &#039;необходимость трансформации символов, False - не трансформируем
    Dim fso, ret
    Dim i, mesaga    
    Dim strNewLogSuf &#039;суффикс имени файла лога
    strNewLogSuf = &quot;-log-&quot; &amp; Date() &amp; &quot;.csv&quot; 
    
    &#039;************** шаблоны **************
    Dim strRemoveCommentsPattern
    &#039;шаблон удаления комментариев
    strRemoveCommentsPattern = _
            &quot;^\s*(?:&#039;|\brem\b).*$|(?:&#039;|\brem\b)[^&quot; &amp; Chr(34) &amp; &quot;]*$|^\s+|\s+$&quot;
    &#039;шаблон объединения строк - символ подчеркивания в конце строки
    Dim strFindJumpPattern
    strFindJumpPattern = &quot;_$&quot; 
    &#039;шаблон для поиска строк с объявлениями
    Dim strGetVarNameTestPattern
    strGetVarNameTestPattern = _
            &quot;\b(?:sub|function|public|static|private|dim|const|class|property)\s+.*&quot;
    &#039;шаблон для удаления из строк с объявлениями
    Dim strGetVarNameReplacePattern
    strGetVarNameReplacePattern = _
            &quot;\b(?:sub|function|public|static|private|dim|const|class|property|get|let|set)\b|\(|\)|,|\t|=.*$&quot;
    
    Const ClassIni = &quot;Class_Initialize&quot; &#039;строка инициализации класса
    Const ClassTerm = &quot;Class_Terminate&quot; &#039;строка удаления класса
    &#039;**************************************
    
    Dim strArr() &#039;массив для строк из файла с кодом    
    Dim strNameArr() &#039;массив имен переменных
    Redim strNameArr(2,0) &#039;необходимо инициализировать, переменные начнутся с индекса №1
    Dim CharArray &#039;массив символов - алфавит :)    
    CharArray = Array(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;)            

    Set fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)

    If WScript.Arguments.Count = 0 Then
        Dim objDialog &#039;диалог выбора файла    
        Set objDialog = CreateObject(&quot;UserAccounts.CommonDialog&quot;)
        If Not IsObject(objDialog) Then 
            MsgBox &quot;Не удалось создать диалоговое окно&quot; &amp; vbCrLf &amp; _
                    &quot;Используйте консольный режим&quot;,vbExclamation
            Set fso = Nothing
            WScript.Quit
        End If
        
        objDialog.Flags = &amp;H0200 &#039;возможность выбрать несколько файлов
        objDialog.Filter = &quot;Visual Basic files (*.vb;*.vbs)|*.vb;*.vbs|Все файлы (*.*)|*.*&quot;    
        
        &#039;открываем диалог    
        ret = objDialog.ShowOpen    
        
        &#039;если файл не выбран - завершаем выполнение скрипта    
        If Not ret Then 
            Set fso = Nothing
            WScript.Quit             
        End If
            
        &#039;вызываем функцию удаления с массивом имен выбранных файлов
        ret = RemComm(Split(Trim(fso.GetFileName(objDialog.FileName))))
        
        Set objDialog = Nothing    
    Else    
        &#039;вызываем функцию удаления с коллекцией аргументов скрипта        
        ret = RemComm(WScript.Arguments)    
    End If
    
    Set fso = Nothing
        
    &#039;вывод информации о ходе выполнения
    mesaga = &quot;Журнал:&quot;
    For i = 0 To UBound(ret,2)
        mesaga = mesaga &amp; vbCrLf &amp; ret(0,i) &amp; &quot; - &quot; &amp; ret(1,i)
    Next
    MsgBox mesaga,vbInformation

&#039;удаление комментариев, переименование переменных и пр.
Function RemComm(arrFiles)
    On Error Resume Next        
    Dim arrRemComm() &#039;массив для лога    
    Dim strFilePath &#039;путь к файлу кода    
    Dim strFile &#039;имя файла в коллекции    
    Dim regEx &#039;регулярные выражения    
    Dim ret(5) &#039;возвращенное значение
    Dim i, j
    &#039;создаем регулярное выражение
    Set regEx = New RegExp 
    With regEx        
        .Global = True   &#039;устанавливаем глобальность применения
        .IgnoreCase = True  &#039;устанавливаем нечувствительность к регистру
    End With
    
    i = 0
    For Each strFile In arrFiles
        &#039;собираем путь к файлу
        strFilePath = fso.BuildPath(fso.GetParentFolderName(fso.GetAbsolutePathName(strFile)), fso.GetFileName(strFile))            
        
        &#039;поверяем наличие файла - пользительно для консольного варианта
        If Not fso.FileExists(strFilePath) Then             
            Redim Preserve arrRemComm(1,i)
            arrRemComm(0,i) = strFilePath
            arrRemComm(1,i) = &quot;Файл не найден&quot;            
        Else                
            &#039;читаем файл - отправляем путь
            ret(1) = ReadFile(regEx,strFilePath)            
            
            If bStir Then &#039;проверяем необходимость переименования переменных
            
                &#039;извлекаем имена функций, процедур, переменных, классов и пр.
                &#039;в public переменную strNameArr
                ret(2) = GetVarName(regEx)            
                
                &#039;переименуем переменные
                ret(3) = RenameVar(regEx)                
            
            End If
            
            &#039;пишем в новый файл
            ret(4) = WriteFile(strFilePath)
            
            &#039;складываем коды выполнения
            Redim Preserve arrRemComm(1,i)
            arrRemComm(0,i) = strFilePath            
            ret(0) = Err.Number
            For j = 1 To UBound(ret)
                ret(0) = ret(0) + ret(j)
            Next            
            &#039;проверяем наличие ошибок
            If Not ret(0) Then
                arrRemComm(1,i) = &quot;Успех&quot;
            Else
                arrRemComm(1,i) = &quot;Ошибка&quot;
            End If            
        End If
        i = i + 1
    Next    
    Set regEx = Nothing
    
    RemComm = arrRemComm    
End Function

&#039;чтение файла и удаление комментариев
Function ReadFile(regEx,strFilePath)
    On Error Resume Next
    Dim objFile &#039;файл с кодом
    Dim i
    &#039;открываем файл с кодом для чтения    
    Set objFile = fso.OpenTextFile(strFilePath,1) 
    i = 0            
    Do While objFile.AtEndOfStream &lt;&gt; True &#039;читаем файл                
        ReDim Preserve strArr(i) &#039;перебиваем размерность массива
        &#039;закидываем строки в массив и по ходу удаляем комменты
        strArr(i) = RemoveComments(regEx,objFile.ReadLine)
        
        If i &lt;&gt; 0 Then
            &#039;если в конце предыдущей строки есть символ переноса строки -
            If FindJump(regEx,strArr(i-1)) Then 
                &#039;объединяем строку с предыдущей
                strArr(i-1) = Left(strArr(i-1),Len(strArr(i-1))-1) &amp; strArr(i) 
                Redim Preserve strArr(i-1) &#039;уменьшаем массив
            Else &#039;если нет символа переноса - продолжаем увеличивать массив
                i = i + 1 
            End If
        Else &#039;первую строку в любом случае читаем и увеличиваем массив
            i = i + 1
        End If                
    Loop
    objFile.Close &#039;закрываем файл
    Set objFile = Nothing &#039;удаляем ссылку на файл
    ReadFile = Err.Number
End Function

&#039;удаление комментариев (вызываем из функции чтения файлов)
Function RemoveComments(regEx,strInput)
    On Error Resume Next    
    regEx.Pattern = strRemoveCommentsPattern &#039;собираем шаблон для удаления     
    RemoveComments = regEx.Replace(strInput,vbNullString) &#039;удаляем комменты и пр.    
End Function

&#039;проверка наличия переноса строки (вызываем из функции чтения файлов)
Function FindJump(regEx,strInput)
    On Error Resume Next    
    regEx.Pattern = strFindJumpPattern
    If regEx.Test(strInput) Then         
        FindJump = True
    Else
        FindJump = False
    End If    
End Function

&#039;получение имен переменных
Function GetVarName(regEx)
    On Error Resume Next
    Dim strMatchesArr()    &#039;массив совпавших строк
    Dim colMatches&#039;, strMatch    
    Dim i, j, k
    Dim strSplitArr
    Dim strFindVarPatternStart &#039;начало строки шаблона для поиска переменной
    Dim strFindVarPatternEnd &#039;конец строки шаблона для поиска переменной
    strFindVarPatternStart = &quot;\b&quot;
    strFindVarPatternEnd = &quot;\b(?!&quot; &amp; Chr(34) &amp; &quot;)&quot;
    i = 0
    &#039;шаблон для поиска строк с объявлениями
    regEx.Pattern = strGetVarNameTestPattern    
    For i = 0 To UBound(strArr) &#039;бежим по массиву строк из файла    
        &#039;проверяем наличие шаблона в строке - наверное так будет быстрее
        If regEx.Test(strArr(i)) Then
            &#039;шаблон для удаления лишнего из строк с объявлениями
            regEx.Pattern = strGetVarNameReplacePattern
            Redim Preserve strMatchesArr(i)
            &#039;заменяем лишнее (согласно шаблону) пробелами
            strMatchesArr(i) = regEx.Replace(strArr(i),Chr(32))    
            &#039;разбиваем строку в массив по пробелу - получаем имена переменных
            strSplitArr = Split(strMatchesArr(i)) 
            &#039;вернули шаблон обратно
            regEx.Pattern = strGetVarNameTestPattern
            &#039;побежали по массиву свежих переменных        
            For j = 0 To UBound(strSplitArr)
                &#039;проверим валидность имени переменной
                If CheckName(strSplitArr(j)) Then
                    &#039;проверим наличие имени переменной в массиве (чтобы не повторяться)                    
                    If Not CheckNameArr(strSplitArr(j),0) Then 
                        k = UBound(strNameArr,2) + 1 &#039;к верхнему индексу добавляем 1
                        Redim Preserve strNameArr(2,k) &#039;перебиваем размерность
                        &#039;добавляем в массив значения
                        strNameArr(0,k) = strSplitArr(j) &#039;имя переменной                         
                        strNameArr(1,k) = GetRandomName(CharArray,intMaxLen,intPro) &#039;новое имя    
                        &#039;проверяем новое имя - возможны повторы
                        Do While CheckNameArr(strNameArr(1,k),1)
                            &#039;если уже есть - формируем новое
                            strNameArr(1,k) = GetRandomName(CharArray,intMaxLen,intPro)
                        Loop
                        &#039;собираем строку шаблона для поиска переменной в строке    
                        strNameArr(2,k) = strFindVarPatternStart &amp; strSplitArr(j) &amp; strFindVarPatternEnd                    
                    End If
                End If
            Next
        End If
    Next    
    GetVarName = Err.Number
End Function

&#039;проверка имени на валидность (вызываем из функции получения имен переменных)
Function CheckName(strName)
    On Error Resume Next    
    &#039;IsNumeric - на случай массивов (число в скобках)    
    If strName = ClassIni Or strName = ClassTerm Or IsNumeric(strName) Then
        CheckName = False
    Else
        CheckName = True
    End If
End Function

&#039;проверка наличия имени переменной в массиве имен переменных
&#039;(вызываем из функции получения имен переменных)
Function CheckNameArr(strName,intIndex)
    On Error Resume Next
    Dim i
    &#039;если проверяем старое имя - вычитаем 0, если новое - 1
    For i = 0 To UBound(strNameArr,2) - intIndex
        If strNameArr(intIndex,i) = strName Then 
            CheckNameArr = True
            Exit Function
        End If
    Next
    CheckNameArr = False
End Function

&#039;получаем случайное имя (вызываем из функции получения имен переменных)
Function GetRandomName(CharArray,intMaxLen,intPro)
    On Error Resume Next
    Dim arrReturnName() &#039;массив случайных букв и цифр для создания имени
    Dim i, j
    Dim strRandomName
    Randomize
    &#039;рандомизируем количество символов в новом имени от 2 до 10
    j = Int((intMaxLen - 1) * Rnd) + 2
    
    Redim arrReturnName(j)
    
    &#039;первый символ - буква
    arrReturnName(0) = CharArray(Int((UBound(CharArray) + 1) * Rnd))
    For i = 1 To j    
        If Rnd &lt; intPro/100 Then &#039;вычисляем процент букв
            arrReturnName(i) = CharArray(Int((UBound(CharArray) + 1) * Rnd))
        Else 
            arrReturnName(i) = Int(10 * Rnd)
        End If
    Next
        
    GetRandomName = Join(arrReturnName,vbNullString)
End Function

&#039;переименование переменных
Function RenameVar(regEx)
    On Error Resume Next
    Dim i, j
    For i = 0 To UBound(strArr) &#039;бежим по массиву строк из файла
        For j = 1 To UBound(strNameArr,2) &#039;дальше по массиву имен переменных
            &#039;устанавливаем шаблон, заготовленный в 3-й размерности массива
            regEx.Pattern = strNameArr(2,j)
            &#039;сначала проверяем - таким образом сокращаем количество итераций
            If regEx.Test(strArr(i)) Then                 
                strArr(i) = regEx.Replace(strArr(i),strNameArr(1,j))    
            End If
        Next
    Next
    RenameVar = Err.Number
End Function

&#039;пишем новый файл
Function WriteFile(strFilePath)
    On Error Resume Next
    Dim objNewFile &#039;новый файл    
    Dim strNewFileName &#039;имя нового файла
    Dim strNewFilePath &#039;путь к новому файлу(с префиксом)
    Dim i
    Dim bTrans &#039;необходимость трансформации символов
    
    &#039;************** константы для трансформации символов **************
    Const strFirstLine = &quot;Execute(&quot; &#039;первая строка нового файла
    Const strLastLine = &quot;vbcrlf)&quot; &#039;последняя строка нового файла    
    &#039;константы для формирования символов новой строки
    Const strCrLf1 = &quot;chr(&quot;
    Const strCrLf2 = &quot;)&quot;
    Const strCrLf3 = &quot; &amp; &quot;
    Const strCrLf4 = &quot; &amp; _&quot;
    &#039;******************************************************************
    
    &#039;собираем имя нового файла
    strNewFileName = strNewNamePref &amp; &quot;-&quot; &amp; fso.GetFileName(strFilePath)    
    &#039;собираем путь к файлу            
    strNewFilePath = fso.BuildPath(fso.GetParentFolderName( _
            fso.GetAbsolutePathName(strFilePath)),strNewFileName)     
    &#039;создаем новый файл, если существует - заменим    
    Set objNewFile = fso.CreateTextFile(strNewFilePath,True) 
    
    &#039;собираем признак необходимости трансформации
    bTrans = bTransChr And CheckTransChr(strArr(i),strFirstLine)
    
    &#039;если трансформируем символы - пишем первую строку
    If bTrans Then objNewFile.Write strFirstLine
        
    &#039;пишем обновленный массив в новый файл
    For i = 0 To UBound(strArr) &#039;пропустим пустые строки            
        If strArr(i) &lt;&gt; vbNullString Then 
            &#039;если трансформируем символы - отправляем строку в функцию трансформации
            If bTrans Then strArr(i) = TransChr(strArr(i)) &amp; _
                    strCrLf1 &amp; GetRandExp(13) &amp; strCrLf2 &amp; strCrLf3 &amp; strCrLf1 &amp; GetRandExp(10) &amp; strCrLf2 &amp; strCrLf4
            objNewFile.WriteLine strArr(i) &#039;пишем строку в новый файл
        End If
    Next
    
    &#039;если трансформируем символы - пишем последнюю строку
    If bTrans Then objNewFile.WriteLine strLastLine    
    
    objNewFile.Close &#039;закрываем файл
    Set objNewFile = Nothing &#039;удаляем ссылку на файл
    
    &#039;запись лога
    If bStir And bWriteLog Then &#039;проверяем необходимость
        &#039;если нет ошибок - пишем лог
        If Not Err.Number Then 
            &#039;собираем путь к файлу лога
            strNewFilePath = fso.BuildPath(fso.GetParentFolderName( _
                fso.GetAbsolutePathName(strFilePath)),strNewFileName &amp; strNewLogSuf)     
            Set objNewFile = fso.CreateTextFile(strNewFilePath,True) 
            objNewFile.WriteLine &quot;True name;Stirred name&quot;
            &#039;пишем обновленный массив в новый файл
            For i = 0 To UBound(strNameArr,2)         
                objNewFile.WriteLine strNameArr(0,i) &amp; &quot;;&quot; &amp; strNameArr(1,i)
            Next
            objNewFile.Close &#039;закрываем файл
            Set objNewFile = Nothing &#039;удаляем ссылку на файл
        End If
    End If
    WriteFile = Err.Number
End Function

&#039;трансформация символов (вызываем из функции записи нового файла)
Function TransChr(strInput)
    Dim ret    
    For i = 1 To Len(strInput)
        ret = ret &amp; &quot;chr( &quot; &amp; GetRandExp(Asc(Mid(strInput,i,1)) ) &amp; &quot; ) &amp; &quot;        
    Next
    TransChr = ret
End Function

&#039;получение случайного выражения 
&#039;(вызываем из функций записи нового файла и трансформации символов)
Function GetRandExp(intChr)
    Dim intRandInt, intRandExp
    Randomize
    intRandInt = Int(rnd * 10000)
    intRandExp = Int(rnd * 3)
    If intRandExp = 0 Then 
        GetRandExp = (intRandInt+intChr) &amp; &quot;-&quot; &amp; intRandInt
    ElseIf intRandExp = 1 Then 
        GetRandExp = (intChr-intRandInt) &amp; &quot;+&quot; &amp; intRandInt
    Else 
        GetRandExp = (intChr*intRandInt) &amp; &quot;/&quot; &amp; intRandInt
    End If
End Function

&#039;проверка файла на необходимость трансформации символов
&#039;False - уже трансформированы
Function CheckTransChr(strInput,strFirstLine)
    If Left(strInput,8) = strFirstLine Then
        CheckTransChr = False
    Else
        CheckTransChr = True
    End If
End Function</code></pre></div><p>Запостил скрипт в <a href="http://forum.script-coding.com/viewtopic.php?id=6135">Коллекцию</a>.</p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-20T12:28:25Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50760#p50760</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50742#p50742" />
			<content type="html"><![CDATA[<p>Как говорил отец-основатель ресурса, считаете нужным — постите в Коллекцию. Если вдруг что окажется не так. дадут SOS — определимся. Исправить Коллекцию можно всегда, запостив новую версию.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2011-08-18T13:50:27Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50742#p50742</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50741#p50741" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Rumata пишет:</cite><blockquote><div class="quotebox"><cite>dab00 пишет:</cite><blockquote><p>Есть проблема?</p></blockquote></div><p>Нет проблем. Спасибо.</p></blockquote></div><p>Я имел ввиду в контексте Вашего совета:<br /></p><div class="quotebox"><cite>Rumata пишет:</cite><blockquote><p>Проведите интересный тест: дайте на &quot;съедение&quot; скрипту...</p></blockquote></div><p>Как-то пафосно про &quot;проблему&quot; получилось <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br /></p><div class="quotebox"><cite>alexii пишет:</cite><blockquote><p>Теперь это, <em>в основном</em>, как бы Ваша головная боль <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" />, коллега — решать, достоин ли Ваш код...</p></blockquote></div><p>Не хотелось бы уважаемой публике фуфло впаривать, поэтому важно мнение специалистов. У кого есть - сообщите.<br />Кроме того запостил скрипт на ресурсах журналов <a href="http://www.vr-online.ru/blog/vbshaker-smeshat-no-ne-vzbaltyvat-4612">VR-Online</a> и <a href="http://forum.procoder.info/index.php/topic,1069.msg9036.html#new">ПРОграммист</a> (кстати, в последнем публиковался в прошлом году со <a href="http://da440dil.narod.ru/scripts.html">статьей</a> про управление USB с помощью VBScript, в результате чего потом слепил <a href="http://da440dil.narod.ru/index.html">вот такое HTA</a>).<br />Я то за свой код, конечно, горой, но, думаю, лучше посмотреть, что люди скажут <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-18T13:29:24Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50741#p50741</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50735#p50735" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>dab00 пишет:</cite><blockquote><p>Есть проблема?</p></blockquote></div><p>Нет проблем. Спасибо.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2011-08-18T10:07:29Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50735#p50735</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50734#p50734" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>dab00 пишет:</cite><blockquote><p>Если считаете скрипт достойным Коллекции - сообщите, запостю. Или сами, если хотите - не возражаю smile</p></blockquote></div><p>Теперь это, <em>в основном</em>, как бы Ваша головная боль <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" />, коллега — решать, достоин ли Ваш код. Равно как и заботиться о его размещении в Коллекции.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2011-08-18T09:47:29Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50734#p50734</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50733#p50733" />
			<content type="html"><![CDATA[<p>Таким образом я тестил. Есть проблема? По-моему отличаются только именами переменных. Количество строк одинаковое. Функционал на месте.</p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-18T08:13:07Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50733#p50733</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50732#p50732" />
			<content type="html"><![CDATA[<p>Проведите интересный тест: дайте на &quot;съедение&quot; скрипту текст самого скрипта А. Получится сжатый скрипт Б. После этого запустите полученный скрипт Б и передайте ему текст Б. Получите скрипт В. Сравните полученные результаты Б и В.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2011-08-18T07:58:23Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50732#p50732</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Удаление комментариев]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=50731#p50731" />
			<content type="html"><![CDATA[<p>Еще раз подмолодил код - похоже финал: устранил один лишний цикл, вынес последний шаблон в переменную и изменил комменты - теперь разберется кодер любой квалификации, если захочет <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br /></p><div class="quotebox"><blockquote><p>Так и назовите - Упрощение, сокращение, минификация, обфускация VBScript-кодов</p></blockquote></div><p>Наверное &quot;VBS: Обфускация VBScript-кода&quot; подойдет. Если считаете скрипт достойным Коллекции - сообщите, запостю. Или сами, если хотите - не возражаю <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2011-08-18T07:51:49Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=50731#p50731</id>
		</entry>
</feed>
