<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; CMD/BAT: Аналог bash на bat]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=10190&amp;type=atom" />
	<updated>2014-11-28T09:21:48Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=10190</id>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88761#p88761" />
			<content type="html"><![CDATA[<p><strong>greg zakharov</strong>, сейчас сверился — таки да, Вы правы: «штатно» — именно оно, «идущее по штату», «состоящее в штатном расписании» и т.п.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-28T09:21:48Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88761#p88761</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88760#p88760" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>Точнее — идущим в комплекте поставки.</p></blockquote></div><p>Если принципально, то - да, по сути - не столь важно.</p>]]></content>
			<author>
				<name><![CDATA[greg zakharov]]></name>
			</author>
			<updated>2014-11-28T08:42:41Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88760#p88760</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88758#p88758" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>Штатным PowerShell стал начиная с семерки,</p></blockquote></div><p>Точнее — идущим в комплекте поставки.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-28T07:58:49Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88758#p88758</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88753#p88753" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>WSH. PoSH.</p></blockquote></div><p>Штатным PowerShell стал начиная с семерки, WSH - более &quot;штатный&quot;.</p>]]></content>
			<author>
				<name><![CDATA[greg zakharov]]></name>
			</author>
			<updated>2014-11-28T06:02:31Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88753#p88753</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88750#p88750" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>logparser под юникс?</p></blockquote></div><p>Нет конечно. Под Windows.</p><div class="quotebox"><blockquote><p>В довесок: обычно большие логи хранятся в сжатом вид,</p></blockquote></div><p>Например? Не припоминаю такого.</p><div class="quotebox"><blockquote><p>а штатных средств для работы с архивами</p></blockquote></div><p>Угу. Нет. Потому как см. выше: я не припоминаю таких логов.</p><div class="quotebox"><blockquote><p>текстовыми файлами в виндоуз практически нет.</p></blockquote></div><p>WSH. PoSH.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-28T03:06:40Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88750#p88750</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88734#p88734" />
			<content type="html"><![CDATA[<p>logparser под юникс?</p><p>В довесок: обычно большие логи хранятся в сжатом вид, а штатных средств для работы с архивами и текстовыми файлами в виндоуз практически нет.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2014-11-27T16:09:14Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88734#p88734</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88733#p88733" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>Когда надо обработать десяток многомегабайтных лог-файлов в поисках заданной строки, то задумываешься, как сократить собственное время ожидания завершения команды.</p></blockquote></div><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><p>Я уже не задумываюсь — LogParser наше всё <img src="//forum.script-coding.com/img/smilies/wink.png" width="15" height="15" />.</p></div></div>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-27T15:02:04Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88733#p88733</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88732#p88732" />
			<content type="html"><![CDATA[<p><strong>mekok</strong><br />Не то чтобы правильнее. Я бы сказал - экономичнее. Хотя в данном случае - повторно прочитать файл в 10 строк - не критично. В данном случае это даже экономия на спичках. <br />Когда надо обработать десяток многомегабайтных лог-файлов в поисках заданной строки, то задумываешься, как сократить собственное время ожидания завершения команды.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2014-11-27T14:54:05Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88732#p88732</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88731#p88731" />
			<content type="html"><![CDATA[<p>Спасибо, взял вариант <strong>alexii</strong> с небольшими правками под себя.<br /><strong>Rumata</strong> ваш вариант может быть более логичен и правилен, но более понятный как-то удобней.</p>]]></content>
			<author>
				<name><![CDATA[mekok]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=32711</uri>
			</author>
			<updated>2014-11-27T14:21:58Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88731#p88731</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88729#p88729" />
			<content type="html"><![CDATA[<p>Не знаю. Наверно - нет. Скорее всего - нет. Данная фраза была сказана без вкладывания смысла в данный атрибут. В тот момент я не имел ввиду искомую подстроку вообще, хотя упомянул ее явно. Согласен - фраза спорная.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2014-11-27T09:58:53Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88729#p88729</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88728#p88728" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>что во входном файле строка с подстрокой Raw_Read_Error_Rate единственная.</p></blockquote></div><p>Бывает несколько?</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-27T09:54:06Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88728#p88728</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88727#p88727" />
			<content type="html"><![CDATA[<p>Ваша задача на баше изначально написана сложно. </p><p>Вот перевод на cmd/bat<br /></p><div class="codebox"><pre><code>
@echo off

set &quot;filename=z.txt&quot;

for /f &quot;tokens=4,6&quot; %%a in ( &#039;
    find &quot;Raw_Read_Error_Rate&quot; ^&lt;&quot;%filename%
&#039; ) do (
    if %%a lss %%b echo:%%a less %%b
)
</code></pre></div><p>Если будете поддерживать башевский вариант может быть стоит сделать так (2 варианта):<br /></p><div class="codebox"><pre><code>
# variant 1: финт с возвратом кода (обратите внимание на восклицательный знак в коде awk)
# 0 - значит значение поля 4 меньше значения поля 6
# 1 - наоборот
if awk &#039;/Raw_Read_Error_Rate/ { exit ! ( $4 &lt; $6 ); } END { exit 1; }&#039; &quot;$filename&quot;
then
</code></pre></div><div class="codebox"><pre><code>
# variant 2: в awk вычисляем разницу, а в шелле сравниваем с нулем
diff_4_6=&quot;$( awk &#039;/Raw_Read_Error_Rate/ { print $4 - $6; }&#039; &quot;$filename&quot; )&quot;
if [ &quot;$diff_4_6&quot; -lt &quot;0&quot; ]
then
</code></pre></div><p>В мире юникс не любят делать двойную работу и если что-то можно сделать в одно действие. то поступают именно так. И еще, я бы не стал закладываться на то, что во входном файле строка с подстрокой Raw_Read_Error_Rate единственная. Думаю, что башизмов в примерах нет.</p>]]></content>
			<author>
				<name><![CDATA[Rumata]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=24846</uri>
			</author>
			<updated>2014-11-27T09:53:00Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88727#p88727</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88726#p88726" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><p>и если какое либо условие не проходит - отправляется письмо.</p></blockquote></div><p>Ну, вот, как-то так (не проверялось):<br /></p><div class="codebox"><pre><code>@echo off
setlocal enableextensions enabledelayedexpansion

set sSourceFile=C:\Песочница\057\0001.txt
set sStrings=Raw_Read_Error_Rate Reallocated_Sector_Ct Seek_Error_Rate

if exist &quot;%sSourceFile%&quot; (
    for %%i in (%sStrings%) do for /f &quot;usebackq tokens=4,6&quot; %%j in (
        `type &quot;%sSourceFile%&quot; ^| find.exe /i &quot;%%~i&quot;`
    ) do (
        set sValueSmart=%%j
        set sThresholdSmart=%%k
        
        if defined sValueSmart (
            if defined sThresholdSmart (
                if !sValueSmart! leq !sThresholdSmart! (
                    echo ValueSmart [!sValueSmart!] less or equal than ThresholdSmart [!sThresholdSmart!]
                    set /a bProblemFound = 1
                ) else (
                    echo ValueSmart [!sValueSmart!] greater than ThresholdSmart [!sThresholdSmart!]
                )
            ) else (
                echo Can&#039;t find [ThresholdSmart] value for [%%~i] parameter.
                exit /b 3
            )
        ) else (
            echo Can&#039;t find [ValueSmart] value for [%%~i] parameter.
            exit /b 2
        )
    )
    
    if defined bProblemFound (
        &quot;C:\sendemail.exe&quot; -f messages@mail -t admin@mail -u PROBLEM: SMART %COMPUTERNAME%
    ) else (
        &quot;C:\sendemail.exe&quot; -f messages@mail -t admin@mail -u OK: SMART %COMPUTERNAME%
    )
) else (
    echo Can&#039;t find source file [%sSourceFile%].
    exit /b 1
)

endlocal
exit /b 0</code></pre></div>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-27T09:51:58Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88726#p88726</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88721#p88721" />
			<content type="html"><![CDATA[<p>Если продублировать - получится не совсем то: он будет выполняться последовательно, по этому будет несколько писем.</p><div class="codebox"><pre><code>@echo off
setlocal enableextensions enabledelayedexpansion

set sSourceFile=C:\smarta.txt

if exist &quot;%sSourceFile%&quot; (
    for /f &quot;usebackq tokens=4,6&quot; %%i in (
        `type &quot;%sSourceFile%&quot; ^| find.exe /i &quot;Raw_Read_Error_Rate&quot;`
    ) do (
        set sValueSmart=%%i
        set sThresholdSmart=%%j
    )

    if defined sValueSmart (
        if defined sThresholdSmart (
            if !sValueSmart! leq !sThresholdSmart! (
                echo ValueSmart [!sValueSmart!] less or equal than ThresholdSmart [!sThresholdSmart!]
                C:\sendemail.exe -f messages@mail -t admin@mail -u PROBLEM: SMART %COMPUTERNAME%
            ) else (
                echo ValueSmart [!sValueSmart!] greater than ThresholdSmart [!sThresholdSmart!]
                C:\sendemail.exe -f messages@mail -t admin@mail -u OK: SMART %COMPUTERNAME% 

            )
        ) else (
            echo Can&#039;t find [ThresholdSmart] value.
            exit /b 3
        )
    ) else (
        echo Can&#039;t find [ValueSmart] value.
        exit /b 2
    )
) else (
    echo Can&#039;t find source file [%sSourceFile%].
    exit /b 1
)

endlocal
exit /b 0</code></pre></div><p>получится что если дублировать цикл проверки, то при каждом проходе будет отправляться сообщение.<br />Если я правильно понимаю.</p><p>А хотелось бы так: сравниваются значения из нужных строк и если какое либо условие не проходит - отправляется письмо.</p><br /><p>Для понятия приведу пример <br /></p><div class="codebox"><pre><code>

ValueSmart2=$(cat /tmp/smartsda.txt | grep Spin_Up_Time | awk &#039;{print $4}&#039;)
ThresholdSmart2=$(cat /tmp/smartsda.txt | grep Spin_Up_Time | awk &#039;{print $6}&#039;)
Opisanie2=&quot;Если VALUE стало меньше THRESH в случае Pre-fail атрибута — существует большая вероятность, что диск вылетит в ближайшие 24 часа. Spin Up Time - время раскрутки пакета дисков из состояния покоя до рабочей скорости. При расчете нормализованного значения (Value) практическое время сравнивается с некоторой эталонной величиной, установленной на заводе. Не ухудшающееся немаксимальное значение при Spin Up Retry Count Value = max (Raw равном 0) не говорит ни о чем плохом. Отличие времени от эталонного может быть вызвано рядом причин, например просадка по вольтажу блока питания.&quot;


ValueSmart3=$(cat /tmp/smartsda.txt | grep Reallocated_Sector_Ct | awk &#039;{print $4}&#039;)
ThresholdSmart3=$(cat /tmp/smartsda.txt | grep Reallocated_Sector_Ct | awk &#039;{print $6}&#039;)
Opisanie3=&quot;Если VALUE стало меньше THRESH в случае Pre-fail атрибута — существует большая вероятность, что диск вылетит в ближайшие 24 часа. Reallocated Sector Count - число операций переназначения секторов. SMART в современных дисках способен произвести анализ сектора на стабильность работы на лету и в случае признания его сбойным, произвести его переназначение.&quot;

ValueSmart5=$(cat /tmp/smartsda.txt | grep Spin_Retry_Count | awk &#039;{print $4}&#039;)
ThresholdSmart5=$(cat /tmp/smartsda.txt | grep Spin_Retry_Count | awk &#039;{print $6}&#039;)
Opisanie5=&quot;Если VALUE стало меньше THRESH в случае Pre-fail атрибута — существует большая вероятность, что диск вылетит в ближайшие 24 часа. Spin Up Retry Count - число повторных попыток раскрутки дисков до рабочей скорости, в случае если первая попытка была неудачной. Ненулевое значение Raw (соответственно немаксимальное Value) свидетельствует о проблемах в механической части накопителя.&quot;


if [ $ValueSmart1 -le $ThresholdSmart1 ]
then
    cat /tmp/smartsda.txt | /usr/local/bin/email -f info@mail.in -n SMART -b -no-encoding $EMAIL -s &quot;PROBLEM: SMART  Raw_Read_Error_Rate, Value=&quot;$ValueSmart1&quot;, Threshold=&quot;$ThresholdSmart1 
elif [ $ValueSmart2 -le $ThresholdSmart2 ]
then
    cat /tmp/smartsda.txt | /usr/local/bin/email -f info@mail.in -n SMART -b -no-encoding $EMAIL -s &quot;PROBLEM: SMART  Spin_Up_Time, Value=&quot;$ValueSmart2&quot;, Threshold=&quot;$ThresholdSmart2
elif [ $ValueSmart3 -le $ThresholdSmart3 ]
then
    cat /tmp/smartsda.txt | /usr/local/bin/email -f info@mail.in -n SMART -b -no-encoding $EMAIL -s &quot;PROBLEM: SMART  Spin_Retry_Count, Value=&quot;$ValueSmart5&quot;, Threshold=&quot;$ThresholdSmart5
else
    cat /tmp/smartsda.txt | /usr/local/bin/email -f info@mail.in -n SMART -b -no-encoding $EMAIL -s &quot;OK: SMART 
fi</code></pre></div>]]></content>
			<author>
				<name><![CDATA[mekok]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=32711</uri>
			</author>
			<updated>2014-11-27T09:14:41Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88721#p88721</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: CMD/BAT: Аналог bash на bat]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=88720#p88720" />
			<content type="html"><![CDATA[<p>Можно продублировать весь участок, начиная с «for /f &quot;usebackq tokens=4,6&quot; %%i in (…», заменив «Raw_Read_Error_Rate» на потребное. Если не то — опишите желаемое подробнее.</p>]]></content>
			<author>
				<name><![CDATA[alexii]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=1844</uri>
			</author>
			<updated>2014-11-27T09:02:44Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=88720#p88720</id>
		</entry>
</feed>
