working from home on my private PC via Citrix with web sessions, skype sessions, ... I'd like to make sure that I've gained privacy after end of work. I've figured out the following batch script to close all job related taskbar tasks by one double click. It's kind of brute force, but a single taskkill (therefor) hasn't done the job on certain (nested) processes in the past. Any suggestions for improvements?
Translations:
ist beendet = e.g. = is terminated
ist nicht beendet = e.g. = is not terminated
Best Regards
Matt
GetPrivacy_v4.bat
#ECHO OFF
ECHO ############# STARTING ###############
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET FILE = ""
SET/A ACTFILE = 0
SET/A MAXFILE = 0
SET/A TRIES = 1
SET "SUCCESS=TRUE"
set "LIST=(msedge.exe AuthManSvr.exe AnyDesk.exe wfcrun32.exe Concentr.exe CtxWebBrowser.exe
SelfService.exe SelfServicePlugin.exe Skype.exe TeamViewer_service.exe
g2mlauncher.exe g2mcomm.exe redirector.exe dropbox.exe Teams.exe)"
for %%x in %LIST% do SET/A MAXFILE += 1
for %%x in %LIST% do (
SET/A ACTFILE += 1
SET FILE=%%x
SET "SUCCESS=TRUE"
SET/A TRIES=1
FOR /L %%T IN (1,1,5) DO (
IF !TRIES! LEQ 5 (
start /MIN taskkill /F /T /IM !FILE! 2>&0
FOR /f "tokens=1-6,* delims=. " %%a IN ('TASKLIST') DO (
IF "%a%" == "!FILE!" SET "SUCCESS=FALSE"
)
IF "%SUCCESS%" == "TRUE" (
SET/A TRIES = 6
) ELSE (
SET/A TRIES = %%T
)
)
)
IF !TRIES! == 6 (
IF "%SUCCESS%" == "TRUE" ( ECHO !ACTFILE!/!MAXFILE!: !FILE! ist beendet )
IF "%SUCCESS%" == "FALSE" ( ECHO !ACTFILE!/!MAXFILE!: !FILE! ist nicht beendet )
)
)
ECHO ############### DONE #################
PAUSE
Related
Is there a piece of code which can be used in a batch file to determine if firstly IE is open, and if so which websites are open in the tab(s)?
I am needing to force close IE when a user locks their PC, and if a specific website is open.
Thanks in advance.
Give a try for this batch file :
#echo off
Title Checking Running Process and Get their command lines
setlocal enabledelayedexpansion
Mode 90,25 & color 0A
Set "ProcessName=iexplore.exe"
Set "String2Search=facebook"
Call :CheckRunning !ProcessName!
If /I "%flag%"=="True" (
color 0A
echo %flag%
Call :GetCommandLine !ProcessName!
echo(
Call :CheckString_in_URL "%String2Search%"
) else (
color 0C
echo %flag%
echo !ProcessName! is not running !
pause>nul & exit
)
Exit
::********************************************************************************************************
:CheckRunning <ProcessName>
Set "ProcessName=%1"
tasklist /NH /FI "imagename eq %ProcessName%" 2>nul |find /i "%ProcessName%" >nul
If not errorlevel 1 ( Set "flag=True" ) else ( Set "flag=False" )
Exit /b
::********************************************************************************************************
:GetCommandLine <ProcessName>
Set "ProcessCmd="
for /f "tokens=2 delims==" %%P in ('wmic process where caption^="%~1" get commandline /format:value ^| findstr /I "%~1" ^| find /I /V "%~nx0" 2^>nul') do (
Set "ProcessCmd=%%P"
echo !ProcessCmd!
)
Exit /b
::******************************************************************************************************
:Kill <ProcessName>
Taskkill /IM "%~1" /F>nul 2>&1
Exit /b
::******************************************************************************************************
:CheckString_in_URL <String2Search>
set "String2Search=%~1"
(
echo Set objFso = CreateObject^("Scripting.FileSystemObject"^)
echo Set colShWindows = CreateObject^("shell.application"^).Windows
echo For Each w In colShWindows
echo If objFso.GetFileName^(LCase^(w.FullName^)^) = "iexplore.exe" Then
echo WScript.Echo w.LocationURL
echo End If
echo Next
)>"%Temp%\iexplore_tabs.vbs"
setlocal EnableDelayedExpansion
for /f %%a in ('cscript //nologo "%Temp%\iexplore_tabs.vbs"') do (
set /a index+=1
set "URL[!index!]=%%a"
)
for /L %%i in (1,1,%index%) do (
echo !URL[%%i]! | find /I "%String2Search%">nul && (
echo Found this string "%String2Search%" in the URL "!URL[%%i]!"
echo(
echo Did you want to kill this process "!ProcessName!" Y/N ?
Set /p "Answer="
If /I "!Answer!"=="Y" ( Call :Kill "!ProcessName!" ) else ( exit )
) || (
echo No string like "%String2Search%" found in "!URL[%%i]!"
Timeout /T 5 /nobreak>nul
)
)
exit /b
::******************************************************************************************************
I'm grateful to aGerman that give me the idea of how to enumerate the URLs of the InternetExplorer tabs
I tried everything I could, but I cannot number the lines in a text file using batch file. I am newbie, want to create CNC program with batch file, by simply click on a bat-file.
I succesfully created the cnc program ( which is a text file,as you can see below ), but cannot give line numbers to it. The number of the lines are different, not always 10, as in this example.
All I need from this:
BEGIN PGM OM11 MM
CALL LBL 101
M323
CYCL DEF 247 DEF. ZERO PEZZO Q339=+1 ; NUMERO ORIGINE
CALL PGM TNC:\master\master-1\001 hdh code masolata.H
CALL PGM TNC:\master\master-1\002 hdh code msolata msolata.h
CALL PGM TNC:\master\master-1\003 hdh code1.H
CALL PGM TNC:\master\master-1\004 hdh code2.h
;
M323
END PGM OM11 MM
to this:
0 BEGIN PGM OM11 MM
1 CALL LBL 101
2 M323
3 CYCL DEF 247 DEF. ZERO PEZZO Q339=+1 ; NUMERO ORIGINE
4 CALL PGM TNC:\master\master-1\001 hdh code masolata.H
5 CALL PGM TNC:\master\master-1\002 hdh code msolata msolata.h
6 CALL PGM TNC:\master\master-1\003 hdh code1.H
7 CALL PGM TNC:\master\master-1\004 hdh code2.h
8 ;
9 M323
10 END PGM OM11 MM
One batch file solution is this:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FileName=File.cnc"
if not exist "%FileName%" endlocal & exit /B
set "LineNumber=0"
set "TempFile=%TEMP%\%~n0.tmp"
del "%TempFile%" 2>nul
(for /F "usebackq eol=| delims=" %%I in ("%FileName%") do (
echo !LineNumber! %%I
set /A LineNumber+=1
))>"%TempFile%"
move /Y "%TempFile%" "%FileName%"
if errorlevel 1 del "%TempFile%"
endlocal
But there are some issues with this batch code:
A line with ^ or ! is not correct updated by this code.
A line starting with | is ignored by this code. The option string eol=| determines the end of line character which is by default ; being the reason for using a different one like | because semicolons at start of a line exist obviously in the files to modify.
Empty lines are ignored by FOR completely.
The advantage is that this solution is faster than the next one:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=File.cnc"
if not exist "%FileName%" endlocal & exit /B
set "LineNumber=0"
set "TempFile=%TEMP%\%~n0.tmp"
del "%TempFile%" 2>nul
(for /F "usebackq eol=| delims=" %%I in ("%FileName%") do (
set "Line=%%I"
setlocal EnableDelayedExpansion
echo !LineNumber! !Line!
endlocal
set /A LineNumber+=1
))>"%TempFile%"
move /Y "%TempFile%" "%FileName%"
if errorlevel 1 del "%TempFile%"
endlocal
Read this answer for details about setlocal and endlocal explaining why the second solution is slower with those two commands within the FOR loop.
In comparison to first batch code this slower solution handles ^ and ! in the lines correct.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
del /?
echo /?
endlocal /?
exit /?
for /?
if /?
move /?
set /?
setlocal /?
Read also the Microsoft documentation about Using Command Redirection Operators for an explanation of >> and 2>nul.
the easiest way is with FINDSTR command:
findstr /n "^" some.file>new.file
and the new.file will have a number line in front of it.
to remove the : before the number:
#echo off
set "file=some.file"
set "new=new.file"
break>"%new%"
for /f "tokens=1* delims=:" %%a do ('findstr /n "^" "%file%"') do (
(echo(%%a %%b)>>"%new%"
)
The following example is just another possibility. The script hasn't been tested, but should work fine as long as file size and line length limitations are not exceeded.
To use the script, run it with the text file as your input parameter; either by entering it as a command line or by simply dragging and dropping the text file onto the script. The output file should be written to the same location as the input file and have the same name but with an .nc extension; (for that reason please don't use *.nc files for input or change nc on line 9 accordingly).
#Echo Off
If Not Exist "%~1" (Echo Input file not found & Exit /B 1)
Set /A ln=0,cnt=1,incr=1
(For /F "Tokens=1* Delims=]" %%A In ('Find /V /N ""^<"%~1"') Do (
Call Echo .%%cnt%%.|Find ".1.">Nul&&(Set /A ln+=1
Call Set /P "=%%ln%% "<Nul
Set /A cnt=incr)||Set /A cnt-=1
Call :Sub "%~1" "%%A]]"
Echo %%B))>"%~dpn1.nc"
:Sub
Find /N /V ""<"%~1"|Find "%~2">Nul||Exit /B
Set /P "=]"<Nul
Call :Sub "%~1" "%~2]"
Bonus: You may also, (although not necessary here), change the %incr% value on line 3 to allow numbering every n lines, where n is an integer e.g. incr=3.
Note: the script assumes that delayed expansion has not been set enabled by default, if it has then it may be prudent to add a new line before the current line 4 which reads SetLocal DisableDelayedExpansion
numberME --- This batch can insert or remove consecutive numbering from your text file into the lines.
Another delimiter to be included can also be specified on request.
Help is included - the English help is included in a cover.
numberMe /L0 /F myFile
-
:: -------------------schnipp------NumberMe.bat------------
::: :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::: #NumberMe.bat Version 1.9 .. put line numbers into Files or delete
::: #Numbering if found or/and/only delete all emty lines wiht or without spaces;
::: #help and progress of batch in german;
::: #[/?en] english short guide, bevor code in batch 1 line behind ::: [/?] Help ;
::: #Version 0.03 Placed into the Public Domain by Biber3#hotmail.de 15.08.2004;
::: #modified from 1.0 - 1.9 by pieh-ejdsch#o2online.de 13.06.2009 - 22.02.2011,
::: #last Versions: 0.03, 1.0, 1.0b thanks to bastla, 1.1 ... 1,9
::: #supportet by www.administrator.de ; Bugs or Updates? Please feedback!
::: #---Put in this code to Editor, save as "all-filetype" named NumberMe.cmd
::: #---For install on Win System: press [WIN]+[R] , then type: %windir%\system32
::: #---press Enter and put in this File to ExplorerWindow which has opened up
::: #---now this Application works in Batch; CMD or [WIN]+[R] by typing this
::: #---BatchName(.cmd) with or without Extension.---------------------------------
::: #------------------------------------------------------------------------------
::: [/?] Help german only, but here is an english short guide for You;
::: Sourcefilename must be the first Option. All other Options from second till
::: sixth can be in much differrent array. Dubbel dot in Options can be lost.
::: Options include no space to string together as /N-/Q/Z -or Seperately or other
::: sourcefilename for working batch always be needed, without target-path-filename only output on Screen;
::: [/f] for aktion in sourcefile or in target-path-filename
::: [/n:1] one-figure numbering with Automated PreZeroNumbering (1-7, 0001-4702)
::: (for example: [/n:5] not less than five-figure numbering-> 00001-00120);
::: [/n:0] setting for without PreZero (1-245);
::: [/n:-] deletes a numbered consecutively before space or Piont if found it
::: - or is it used to test for -> gives exitcode 5;
::: without [/n:] Auto PreZeroNumbering with not less than two-figure number just like [/n:2];
::: - only with [/n:] setting for without Numbering;
::: if you substitute [/N:] by [/L:] NumberMe will not be delete all empty lines,
::: syntax (behind dubble dot) takes effekt like than [/N:];
::: [/l:-] Denumbering without cleaning empty Lines;
::: [/Z:] change delimiter: space by point; or behind : Input other Delimiter(s)
::: to include Spaces or additional characters after delimiter ->Syntax must insert
::: between quotation marks for denumbering and incluce string to remove for,
::: -> be sure in string 1st and the last sign is not a number
::: ->be sure in string the last sign exist once;
::: [/Q] Quit modus: no Program message; been related works with E [/QE]
::: [/E] Quit modus: no Error message; been related works with Q [/EQ]
::: > Spaces for Path-File-Name or additional characters must insert between quotation marks;
::: > if source(path)name is equal to target(path)name NumberMe will be effect all
::: > in sourcefile and without Options [/Z] [/N|/L] [only deletes all empty lines;
::: > additional characters only displayed false on Screen;
::: output from sourcefile: number of all Lines and all empty Lines;
::: Programm messages Piped into the Handle 3
::: Error messages Piped into the handle 2
::: -------------------------------------------------------------------------------
::: EXITCODES: [0] successful; [1] put in filename; [2] sourcefile not found;
::: [3] input incorrect Syntax; [4] file is empty;
::: [5] file is not numbered consecutively; [6] file is without empty lines only
::: [7] file is with empty lines only;
::; :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#echo off & setlocal disabledelayedexpansion
for %%i in ("pN=2" "b=" "b2=" "E=" "Q=" "Full=0" "noempty=0" "Zahlen=" "D=" "emptylines=" "erropt=" "NN=" "pOut=" "put=" "yes=1" "orig=" "vpn=" "nodel=" "Zeichen= " "noemptyLines=" "LL=" "L=" "O=" "um=" "F=") do set "%%~i"
::Syntaxpruefung: Quelle, Ziel, De- oder Nummerierung
:Parameter
set "Opt="%1""
setlocal enabledelayedexpansion
if "!Opt!" == """" ( endlocal&goto :Paraend) else set "Opt=!Opt:"=!"
if "!Opt!" == "/?" endlocal&goto :help
for %%i in ("/" "/help" ) do if /i "!Opt!"=="%%~i" endlocal&goto :help
if /i "!Opt!"=="/?en" endlocal&for /f "usebackq tokens=1,*" %%i in ("%~f0") do if "%%i" == "::;" (echo %%j& exit /b 0) else if "%%i" == ":::" echo %%j
(for /f "delims=" %%i in ("!Opt!") do endlocal&set "Opt=%%i") || (endlocal&shift /1 &goto :Parameter)
:2ndParam
if not "%Opt:~ 0, 1%" =="/" ( set "SL=") else set "SL=/"
for /f "tokens=1,* delims=/" %%a in ("%Opt%") do (
if "%%b" == "" ( set "Opt=") else set "Opt=/%%b"
set "px=%%a"
)
if not defined SL goto :InandOut
if "%px:~1,1%" == ":" set "px=%px:~0,1%%px:~2%"
if /i "%pX:~0,1%" == "Z" (
set /a yes + = 1
if "%pX:~1%" == "" ( set "Zeichen=.") else set "Zeichen=%pX:~1%"
) else if /i "%pX%" == "E" ( set "E=>nul"
) else if /i "%pX%" == "EQ" ( set "E=>nul" & set "Q=>nul"
) else if /i "%pX%" == "Q" ( set "Q=>nul"
) else if /i "%pX%" == "QE" ( set "E=>nul" & set "Q=>nul"
) else if /i "%pX:~0,1%" == "N" (
set /a yes + = 1
if "%pX:~1%" == "-" ( set "pN=D"
) else if "%pX:~1%" gtr "0" ( set /a pN = %pX:~1%
) else if "%pX:~1%" == "0" ( set "pN=0"
) else set "pN=N"
) else if /i "%pX:~0,1%" == "L" (
set /a yes + = 1
set L=1
if "%pX:~1%" == "-" ( set "pN=D"
) else if "%pX:~1%" gtr "0" ( set /a pN = %pX:~1%
) else if "%pX:~1%" == "0" ( set "pN=0"
) else set "pN=N"
) else if /i "%pX%" == "F" ( set "O=1"
for %%i in ("%px:~1%") do set "pOut=%%~dpi" & set "put=%%~nxi" & set "um=>>" & set "F=""
) else set "erropt=%pX%"
if defined Opt (goto :2ndParam) else shift /1 &goto :Parameter
:InandOut
if defined Input if not defined pOut for %%i in ("%px%") do set "pOut=%%~dpi" & set "put=%%~nxi" & set "um=>>" & set "F=""
if not defined Input for %%i in ("%px%") do set "InFile=%%~nxi"&set "Input=%%~i"
if defined Opt goto :2ndParam
shift /1 &goto :Parameter
:Paraend
for %%i in ("" "\" "." ".." "..." "....") do if "%Input%"=="%%~i" (echo Syntaxfehler! Bitte Quelldateinamen angeben! & set b=1 & goto :help )>&2
if not exist "%Input%" set b2=1 & goto :end
:: Zaehle Zeilen
findstr /n "^" "%Input%">"%temp%\Ltmp"
for /f "delims=:" %%i in ('find /c ":"^<"%temp%\Ltmp"') do set /a Full = %%i
(for /f "usebackq tokens=* delims=" %%i in ("%Input%") do #for /f %%j in ("%%i") do #echo.%%i
)>"%temp%\tmp"
findstr /n "^" "%temp%\tmp">"%temp%\Ftmp"
for /f "delims=:" %%i in ('find /c ":"^<"%temp%\Ftmp"') do set /a noempty = %%i
if defined erropt ( echo ungueltige Option: %erropt% %E%
goto :syntax)>&2
::ist Quelle gleich Ziel? gleich Numberme?
if "%pOut%%put%" == "%~f0" set "orig=" & set "pOut=" & set "put=" & set "F=" & set "um="
if defined O if not defined output for %%i in ("%Input%") do set "pOut=%%~dpi" & set "put=%%~nxi" & set "um=>>" & set "F=""
if "%pOut%%put%" == "%Input%" set orig=%random%
if not defined O if defined orig if %yes% equ 1 set pN=N
if %Full% equ 0 goto :end
goto :next
:help
if defined b (echo. & echo gueltige Syntax: %E% & goto :syntax)>&2
echo Listet Dateien ^(mit Nummerierung^) zeilenweise ^(ohne Leerzeilen^) auf den
echo Bildschirm oder in eine Datei. Oder Entfernt die Nummerierung.
:syntax
(echo. & echo %~n0 [Laufwerk:][Pfad]Quelldatei [/F][Laufwerk:][Pfad][Zieldatei] %E%
echo [/N^|/L[:][WERT]] [/Z[:][ZEICHEN]] [/Q] [/E] %E%
echo [/?] Hilfe [/?en] credits and english short guide %E%
if defined b ( exit /b 1) else if defined erropt goto :end)>&2
echo.&echo Quelldatei Muss vor der Zieldatei angegeben werden.&echo.
echo Zieldatei Wird die Zieldatei nicht angegeben wird der Inhalt auf dem
echo Bildschirm ausgegeben. Zieldatei Wird ueberschrieben.
echo OHNE AusgabeART wird OHNE Leerzeilen mit Vornullen und Minimum Zweistellig
echo Numeriert ^= [/l:2]. &echo.
echo Wenn Quell-Pfad-Datei und Ziel-Pfad-Datei gleich: Werden in der Quelldatei
echo OHNE AusgabeART und OHNE Option Z oder F NUR Leerzeilen entfernt.
echo Sonst wie Syntax.&echo.
echo /F Aktion in der Quelldatei ^(oder im Angegebenen Ziel^)&echo.
echo /N Gibt die AusgabeART an. OHNE Leerzeilen!
echo /L Gibt die AusgabeART an. MIT Leerzeilen!
echo WERT Wird WERT NICHT angegeben wird NICHT Nummeriert!
echo - Eine gefundene Durchgehende Nummerierung
echo mit Punkt oder
echo mit Doppelpunkt oder
echo mit LeerZeichen
echo ODER wie ZEICHEN wird Entfernt und
echo gibt exitcode 5 wenn Durchgehende Nummerierung fehlt.
echo Bei Option L- werden Leerzeilen nicht entfernt.&echo.
echo 0 Es wird ohne Vornullen Nummeriert.
echo 1 Ab der Zahl 1 wird Automatisch Vorgenullt (1-7, 0001-4702)
echo Oder Mindestene Stellenanzahl inklusive Vornullen (3^= 001-054)&echo.
echo /Z Trennzeichen zwischen Nummerierung und Text wird zum Punkt oder
echo wie ZEICHEN.
echo Fuer ZEICHEN : muss der Optionale Doppelpunkt auch mit angegeben
echo werden. /Z::
echo ZEICHEN Angabe von ein oder mehr Trennzeichen zur de- oder Nummerierung.&echo.
echo Achtung! Fuer Enthaltene Leer-/Sonderzeichen Syntax in " " setzen!
echo Beispiel: /z": :" ^(mindestens das Sonderzeichen muss Umschlossen sein^)
echo Bei Denummerierung gibt das erste Zeichen das Trennzeichen hinter
echo der Nummerrierung an, das letzte Zeichen bis wohin geloescht
echo wird. -^> Zeichenfolge wird Ueberprueft. Bei Denummerierung
echo keine Ziffern als erstes oder letztes Zeichen Verwenden.
echo Das letzte Zeichen nicht doppelt Verwenden.&echo.
echo /Q Meldungen werden NICHT Ausgegeben - Hilfe wird immer angezeigt!
echo /E Entspricht 2^>nul Errormeldungen werden NICHT Ausgegeben. ODER
echo /QE or /EQ Unterdrueckung aller Meldungen in einer Option!&echo.
echo Optionen koennen zusammenhaengend geschrieben werden zB: /N1/QE/Z wenn die
echo einzelne Option Z Keine Leerzeichen enthaelt. Doppelpunkte sind Optional.&echo.
echo Sonderzeichen: Falsche Ausgabe Nur auf Bildschirm! Im Dateiname:-^> setze " " &echo.
echo Die Anzahl Zeilen und Anzahl Leerzeilen der Quelldatei werden ausgegeben!&echo.
echo Statusmeldungen werden im Handle 3 ausgegeben
echo Errormeldungen werden im Handle 2 ausgegeben
exit /b 0
:next
::Statusmeldung für Vorgang
( ::Wenn Nummerierung entfernen
if %pN% == D (
if %noempty% gtr 0 (
if not "%pOut%" == "" (
if defined L ( echo(
echo Nummerierung wird in "%put%" enfernt!
) else ( echo(
if %noempty% lss %Full% (
echo Leerzeilen, Nummerierung werden in "%put%" enfernt!
) else echo "%put%" enthaelt keine Leerzeilen, Nummerierung wird entfernt!
) ) ) else set emptylines=1 & goto :end
) else if not %pN% == N (
::Wenn Nummeriert werden soll
if defined L (
if not "%pOut%" == "" (
if %noempty% lss %Full% ( echo(
echo "%put%" wird Nummeriert!
) else ( echo(
echo "%put%" enthaelt keine Leerzeilen, wird Nummeriert!
) ) ) else if %noempty% equ 0 ( set emptylines=1 & goto :end
) else if not "%pOut%" == "" ( echo(
echo "%put%" wird ohne Leerzeilen Nummeriert!
) )
::Wenn Leerzeilen entfernen
if %pN% == N (
if not defined L if %noempty% gtr 0 (
if %noempty% lss %Full% (
if not "%pOut%" == "" ( echo(
echo Leerzeilen werden in "%put%" enfernt!
) ) else set noemptyLines=1 & goto :end
) else set emptylines=1 & goto :end
) ) %Q% >&3
::Loesche vorhandene Zieldatei
if not "%pOut%%orig%%put%" == "" if exist "%pOut%%orig%%put%" del "%pOut%%orig%%put%"
::Erstelle extraDatei/Output fuer Leerzeilenentfernung oder Tempdatei fuer De- oder Nummerierung
if defined L if %pN% == N (
findstr "^" "%Input%" %um%%F%%pOut%%orig%%put%%F%
goto :end
)
if %pN% == N (
findstr "^" "%temp%\tmp" %um%%F%%pOut%%orig%%put%%F%
goto :end
)
if defined L if not %pN% == D set /a LL = Full & copy "%temp%\Ltmp" "%temp%\Ftmp" >nul
if not defined LL set /a LL = noempty
set NL=9
::mit oder ohne Vornull?
if %pN% == D ( set "D=1"
set "NN=0"
goto :noZero
) else if %pN% lss 1 ( set "NN=0"
goto :noZero
) else set "NN=1"
::Zaehlen der Automatischen oder Manuellen Vornullen
:testZero
if %NL% lss %LL% ( set "NL=%NL%9"
set /a NN + = 1
goto :testZero
)
if %NN% gtr %pN% ( set pN=%NN%) else set NN=%pN%
set NL=9
::Vornullen setzten
:withZero
if not %pN% == 1 ( set "vpn=%vpN%0"
set /a pN - = 1
goto :withZero
)
::Spungziel bei keinen Vornullen oder nach Pruefung auf Nummerierung
:noZero
set /a pN = 0 , HNL = 0 , HL = 9
::Blockanfang De- oder Nummerierung
:read
::Keine Nummerierung gefunden?
if defined nodel if "%Zeichen%" == " " ( set "nodel="
set "Zeichen=."
goto :noZero
) else if "%Zeichen%" == "." ( set "nodel="
set "Zeichen=:"
goto :noZero
) else goto :end
::Schalter fuer Pruefung auf vorhandene Nummerierung oder Sprung zum Ende oder Einstellung Ziffernbreite
if defined D (
if %pN% == %LL% (
if not defined delNR (
set "delNR=1"
goto :noZero
) else goto :end
) else ( set /a pN + = 1
) ) else if %pN% == %LL% ( goto :end) else set /a pN + = 1
::Zaehler fuer Zeile und VorNullen Einstellung und Ruf Zeilenwahl
call :setline %pN%
if %HL% == %pN% ( set "HNL=%NL%"
set "HL=%HL%9"
)
if %NN% gtr 0 if %NL% == %pN% ( set "NL=%NL%9"
set /a NN - = 1
set "vpN=%vpN:~1%"
)
goto :read
::Zeilenauswahl zum Ueberspung
:setline
if 1 == %1 set "skip=" & goto :write
set /a skip = %1 - 1
set skip=Skip=%skip%
:write
::Test auf oder Entfernung einer Vorhandenen Nummerierung
if defined D (
if not defined delNR (
for /f "usebackq tokens=1,* delims=:" %%i in ("%temp%\Ltmp") do (
if defined nodel goto :eof
for /f "delims=%Zeichen:~-1%" %%k in ("%%j") do (
for /f "tokens=1,* delims=%Zeichen:~0,1%" %%l in ("%%k") do (
for /f "tokens=* delims=0" %%n in ("%%l") do if not "%%n%%m" == "%%i%Zeichen:~1,-1%" set "nodel=1"
) ) )
set "pN=%LL%" & goto :eof
) else (
for /f "delims=" %%h in ("%Zeichen%") do (
for /f "usebackq tokens=* delims=" %%i in ("%temp%\tmp") do (
set "Zeile=%%i"
setlocal enabledelayedexpansion
set "Zeile=!Zeile:*%%h=!"
if defined L ( echo(!Zeile!
) else for /f %%j in ("!Zeile!") do echo(!Zeile!
endlocal
) )%um%%F%%pOut%%orig%%put%%F%
set "pN=%LL%" & goto :eof
) )
::Nummerieren
(
for /f "usebackq %skip% tokens=*" %%i in ("%temp%\Ftmp") do (
set "Zeile=%%i"
setlocal enabledelayedexpansion
for /f "delims=:" %%h in ("%%i") do set "HNNR=%%h"
for %%j in ("!HNNR!") do (
set "Zeile=!Zeile:*:=!"
echo.%vpN%%%~j%Zeichen%!Zeile!
if %%~j equ %LL% endlocal & set "pN=%%~j" & goto :eof
if %%~j equ %HL% endlocal & set "pN=%%~j" & goto :eof
endlocal
) ) )%um%%F%%pOut%%orig%%put%%F%
:end
( if defined b2 ( echo Fehler! Quelldatei "%InPut%" nicht gefunden! %E%
exit /b 2)
( echo( %E% %Q%
) >&3
if defined nodel echo "%InFile%" enthaelt keine Nummerierung! %E%
if defined noemptyLines echo "%InFile%" enthaelt keine Leerzeilen %E%
if defined emptylines echo "%InFile%" enthaelt nur Leerzeilen %E%
if %Full% equ 0 echo "%InFile%" ist leer! %E%
) >&2
if %Full% equ 0 goto :noren
if not defined orig goto :noren
if defined erropt goto :noren
if defined emptylines goto :noren
if defined noemptyLines goto :noren
if defined nodel goto :noren
move /y "%pOut%%orig%%put%" "%Input%" >nul
:noren
set /a Lempty = Full - noempty
( echo AnzahlZeilen %Full% AnzahlLeerzeilen %Lempty% %Q%
) >&3
if exist %temp%\Ftmp del %temp%\Ftmp
if defined erropt exit /b 3
if %Full% equ 0 exit /b 4
if defined noemptyLines exit /b 6
if defined nodel exit /b 5
if defined emptylines exit /b7
exit /b 0
:: -------------------schnapp------NumberMe.bat------------
I have another script created because I noticed that a 2 GB file is not processed in the Forloop.
In addition, a file without a final line return from Findstr is not terminated - because the command hangs.
To the 32 bit problem I have another counting function built in. This takes much longer than when using findstr to write a new file.
Only lines up to 1023 bytes are supported.
#echo off
if "%~1" == ":readin" goto :readin
if NOT exist "%~1" >&2 echo File not found!& exit /b 1
if "%~2" == "" ( set "pipe=") else set pipe=^>%2
cmd /v /c ^""%~f0" :readin "%~2" ^<"%~1"^"
exit /b 0
:readin
set /a exit=0
rem Nblock
set /a BlockA= BlockB= BlockC= 0
set "FullBlock=0"
set "BlockMax=1000000000"
set /a TwoMax=2*BlockMax
%pipe% (
for /l %%L in (0) do (
set "Line="
set /p "Line="
if NOT defined Line ( set /a "exit+=1"
if !exit! geq 25 exit
) else (
echo !FullBlock! !Line!
set /a BlockA =BlockA %%BlockMax +1 +BlockMax ,^
BlockB =BlockB %%BlockMax +BlockA/TwoMax +BlockMax ,^
BlockC =BlockC %%BlockMax +BlockB/TwoMax +BlockMax ,exit=0
for /f "tokens=* delims=0" %%D in ("!BlockC:~1!!BlockB:~1!!BlockA:~1!") do set "FullBlock=%%D"
)
)
)
exit /b 1
I was wondering...
I have a program, and I want to charge money for it.
it runs on Windows, and is written mostly in VB and Batch-files...
how can I force the user to buy a product key for it, and activate it to use the Paid Version?
Thanks in advance!
~ #Cascading-style
This just a little example showing you that you can limit the number of execution of your program , so if the maximum of number of execution is reached the program will Auto delete by him self
#echo off
Setlocal enabledelayedexpansion
Title Count the number of times my BATCH file is run
Mode Con Cols=70 lines=7 & color 0E
Set /a MaxExecution=3
set /a count=1
set "FileCount=%tmp%\%~n0.dll"
If Not exist "%FileCount%" (
echo !count! > "%FileCount%"
) else (
For /F "delims= " %%a in ('Type "%FileCount%"') Do (
set /a count=!count! + %%a
echo !count! > "%FileCount%"
)
)
echo.
echo This Program is running for "!count!" time(s)
Call :SelfDelete
pause>nul & Exit /b
::**************************************************************
:SelfDelete
echo.
If !count! GTR !MaxExecution! (
Color 0C
echo The maximum execution of this "%~nx0" is set to "!MaxExecution!"
echo and it is reached & Timeout /T 5 /Nobreak>nul & Del %~f0
) else (
echo The counting is "!count!" and the max is set to "!MaxExecution!"
)
Goto :EOF
::**************************************************************
My internet is not always working properly and I'd like to check the quality based on the cmd windows tool. I believe it's a task simple enough for it to handle.
I've begun by making a shortcut so I can have easy access to the command:
C:\Windows\System32\PING.EXE 8.8.8.8 -t
Now I was trying to transform the cmd ping command into a visually responsive one based on the output. I'd like to make the color change according to the time response.
After looking and not finding anything related, I believe it's either impossible or no one has ever tried.
Thank you very much :)
PD: (In case there was anything unclear just ask and I'll gladly answer)
Based on Magoo's post, I wrote this little batch program.
It asks for the target, the number of requests to make, the max time allowed and the time between requests and then prints in red if the request is over the time max, otherwise it sums the number of requests. It includes timestamp to be more accurate.
Copy and paste in a text file and name it with extension ".bat" (But don't name it "ping.bat" otherwise the program will enter in an infinite loop).
REM CMD PING TOOL
REM By Daweb
REM https://stackoverflow.com/users/3779294/daweb
#ECHO OFF
REM Needed for Line colored
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=1,2 delims=#" %%a IN ('"PROMPT #$H#$E# & echo on & for %%b in (1) do rem"') do (
SET "DEL=%%a"
)
for /f %%a in ('copy /Z "%~f0" nul') do set "CR=%%a"
ECHO *****************
ECHO * CMD PING TOOL *
ECHO *****************
REM Start
:start
ECHO.
ECHO Set yours values
REM SET Target
SET /p hostInput=" - Target (ip or hostname): "
If "%hostInput%"=="" ECHO.&GOTO start
REM SET loops
SET /p loopsInput=" - Requests number: "
SET /a loops=loopsInput
REM SET time limit
SET /p maxmsInput=" - Maximum Time Limit (ms): "
SET /a maxms=maxmsInput
REM Value used for sleep between loops
SET /p sleepInput=" - Delay between requests (s): "
SET /a sleepDelay=sleepInput+1
REM Variables
SET displayText=""
SET /a countRequestsOk=0
SET /a countRequestsKo=0
SET /a totalRequests=0
SET /a maxTime=0
ECHO.
ECHO START at %TIME% [target: %hostInput%, requests: %loops%, time limit: %maxms% ms, delay: %sleepInput% s]
ECHO.
REM Loop
:loop
REM Set time
FOR /f "tokens=1-3 delims=/:" %%a IN ("%TIME%") DO (SET mytime=%%ah%%bm%%cs)
REM Get ping value
FOR /f "tokens=3delims==" %%a IN ('PING -n 1 %hostInput%') DO FOR /f "delims=m" %%b IN ("%%a") DO (
SET /a timems=%%b
SET /a totalRequests+=1
REM Check result
IF !timems! GTR %maxms% ( GOTO failed ) ELSE ( GOTO success )
)
REM Request success
:success
SET /a countRequestsOk+=1
IF !timems! GTR !maxTime! ( SET /a maxTime=timems )
<nul set /P "=!countRequestsOk! requests [Max !maxTime! ms]!CR!"
GOTO next
REM Request failed
:failed
IF !countRequestsOk! GTR 0 ECHO.
SET /a countRequestsOk=0
SET /a countRequestsKo+=1
SET displayText=" %mytime% - !timems!ms"
CALL :ColorText 0c !displayText!
GOTO next
REM Next loop
:next
REM Sleep a little bit
IF %sleepDelay% GTR 1 ( ping -n %sleepDelay% localhost > nul )
REM Check continue
SET /a loops-=1
IF %loops% gtr 0 GOTO loop
REM Display result
IF !countRequestsOk! GTR 0 ECHO.
ECHO.
ECHO STOP at %TIME%
ECHO.
if !countRequestsKo! GTR 0 (
SET displayText="FAILED - !countRequestsKo! requests over %maxms% ms on !totalRequests! requests in total"
CALL :ColorText 0c !displayText!
) ELSE (
SET displayText="SUCCESS - No request over %maxms% ms on !totalRequests! requests in total"
CALL :ColorText 02 !displayText!
)
REM Ask if restart
ECHO.&ECHO *********************
SET /p restartInput="Do it again ? (Y/N): "
If "%restartInput%"=="" ECHO *********************&GOTO start
If /I "%restartInput%"=="y" ECHO *********************&GOTO start
If /I "%restartInput%"=="n" ECHO *********************&GOTO end
REM End
:end
PAUSE
GOTO :EOF
REM Line color
:ColorText
ECHO off
ECHO %DEL% > "%~2"
FINDSTR /v /a:%1 /R "^$" "%~2" NUL
DEL "%~2" > NUL 2>&1
#ECHO OFF
SETLOCAL
SET loops=10
:loop
FOR /f "tokens=3delims==" %%a IN ('PING 8.8.8.8 -n 1') DO FOR /f "delims=m" %%b IN ("%%a") DO ECHO %%b&COLOR %%b&GOTO cchgd
:cchgd
PAUSE
SET /a loops-=1
IF %loops% gtr 0 GOTO loop
COLOR
GOTO :EOF
A simple demonstration - repeats the ping 10 times, changing colours depending on the response. Manipulate to do as you wish...
I am not sure that I know what the desired output should be, but this will output GREEN text for response times 0-39 ms, YELLOW for 40-79 ms, and RED for 80+ ms.
Run this from a cmd.exe prompt using the following command or put it into a .bat file script. Change the directory to the location where the Get-PingColor.ps1 file is landed.
powershell -NoLogo -NoProfile -File "%USERPROFILE%\bin\Get-PingColor.ps1"
=== Get-PingColor.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string[]]$ComputerNames
,[Parameter(Mandatory=$false)]
[int]$Count = 4
,[Parameter(Mandatory=$false)]
[int]$SpeedMinimumSlow = 80
,[Parameter(Mandatory=$false)]
[int]$SpeedMinimumMedium = 40
)
foreach ($ComputerName in $ComputerNames) {
$Pings = Test-Connection -ComputerName $ComputerName -Count $Count
$Average = ($Pings | Measure-Object -Property responsetime -Average).Average
$ForegroundColor = 'Green'
if ($Average -ge $SpeedMinimumSlow) { $ForegroundColor = 'Red'}
else { if ($Average -ge $SpeedMinimumMedium) { $ForegroundColor = 'Yellow' }}
Write-Host -ForegroundColor $ForegroundColor -BackgroundColor 'Black' "$ComputerName $Average ms"
}
=== Execution examples
I am loathe to put images into a post, but I do not see a way to produce color on SO.
I'm looking to create a checklist in a console window to help users choose certain options they would like to install. This kind of output:
Please select options to install:
[x]Option 1
[ ]Option 2
>[x]Option 3
[x]Option 4
Where the user can move the cursor throughout the list and select the options.
I have a very, very vague idea of how I might do this code, testing with just two options. But if there is anyone who already has a solidified idea of how this would work and could share I would be very appreciative!
Test code for those who want to see it:
#echo off
call:main
end /b 0
:main
set /p choice= "Would you like to enable option one? (yes/no): "echo(
if %choice%==yes (
set option1=1
)
if %choice%==no (
set option1=0
)
call:mod1
set /p choice= "Would you like to enable option two? (yes/no): "echo(
if %choice%==yes (
set option2=1
)
if %choice%==no (
set option2=0
)
call:mod2
:mod1
if %option1%==1 (
echo [x] Option 1
)
if %option1%==0 (
echo [ ] Option 1
)
:mod2
if %option2%==1 (
echo [x] Option 1
)
if %option2%==0 (
echo [ ] Option 1
)
You could try this:
#echo off
setlocal EnableDelayedExpansion
for /f %%A in ('"prompt $H &echo on &for %%B in (1) do rem"') do set BS=%%A
set "getKeyMacro=powershell -noprofile "^
while (-not (37..40+13).contains($x)) {^
$x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
}^
if ($x -eq 13) {^
'enter'^
}^
('left','up','right','down')[$x - 37]^
""
set "option1=0"
set "option2=0"
set "option3=0"
set "option4=0"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,4) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! Option %%G
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr 4 set "selected=4"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select
:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select
:OK
FOR /L %%G IN (1,1,4) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause
Note that this is very heavily dependent on Delayed Expansion, so you might want to read up on it here.
Second note: this needs powershell so you can use up and down arrow keys to select options, enter to toggle currently selected option, and right arrow to continue.
EDIT
Updated version, this allows you to set the display names for the options, but you need to specify the amount of options aswell:
#echo off
setlocal EnableDelayedExpansion
for /f %%A in ('"prompt $H &echo on &for %%B in (1) do rem"') do set BS=%%A
set "getKeyMacro=powershell -noprofile "^
while (-not (37..40+13).contains($x)) {^
$x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
}^
if ($x -eq 13) {^
'enter'^
}^
('left','up','right','down')[$x - 37]^
""
set "option1=0"
set "option2=0"
set "option3=0"
set "option4=0"
set "option1name=Install thing 1"
set "option2name=Do thing 2"
set "option3name=Execute thing 3"
set "option4name=Run thing 4"
set "maxOptions=4"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,%maxOptions%) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! !option%%Gname!
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr %maxOptions% set "selected=!%maxOptions%!"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select
:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select
:OK
FOR /L %%G IN (1,1,%maxOptions%) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause
EDIT #2
Now uses the for loop by #Aacini to initiate the variables so this only needs to happen once, and so there is no need for a manual maxoption any more:
#echo off
setlocal EnableDelayedExpansion
set "getKeyMacro=powershell -noprofile "^
while (-not (37..40+13).contains($x)) {^
$x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
}^
if ($x -eq 13) {^
'enter'^
}^
('left','up','right','down')[$x - 37]^
""
set "num=0"
for %%a in ("Install thing 1"
"Do thing 2"
"Execute thing 3"
"Run thing 4") do (
set /A num+=1
set "option!num!=0"
set "option!num!name=%%~a"
)
set "maxOptions=%num%"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,%maxOptions%) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! !option%%Gname!
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr %maxOptions% set "selected=!%maxOptions%!"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select
:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select
:OK
FOR /L %%G IN (1,1,%maxOptions%) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause
#echo off
setlocal EnableDelayedExpansion
rem Define the text for the options
set "num=0"
for %%a in ("First option"
"Second option"
"Third option"
"Fourth option") do (
set /A num+=1
set "msg[!num!]=%%~a"
set "opt[!num!]= "
)
set "digits=0123456789"
:select
(cls
echo Press digit to mark/unmark options, or X to end
echo/
for /L %%i in (1,1,%num%) do echo !digits:~%%i,1!. [!opt[%%i]!] !msg[%%i]!
)
choice /C !digits:~1,%num%!X /N > NUL
if %errorlevel% gtr %num% goto endSelect
set "sel=%errorlevel%"
if "!opt[%sel%]!" equ "X" (set "opt[%sel%]= ") else set "opt[%sel%]=X"
goto select
:endSelect
echo/
echo/
for /L %%i in (1,1,%num%) do (
if "!opt[%%i]!" equ "X" (
echo %%i selected
)
)