I've recently changed jobs and I get to get my hands dirty on some scripting which I've always wanted to learn. I was given an existing batch file and wanted to gussy it up. Previously, this batch file would scan an IP addressed that you are prompted to enter. I want to change this to loop the command based on a list of IP addresses from a text file, only I'm having problems doing that.
I figured that I can do this one of two ways:
1) Run a batch file that will get the IP address, then run the 2nd batch based on that IP address.
OR
2) Just use the one existing batch file and change that to loop based on the IP address on each line of the text file.
What would be the better way to go, and how would you accomplish both?
For #1 I tried to do this, but I don't know how to run the command based on what I'm entering. An example of this would be to run batch.bat 192.168.1.1, which in batch.bat it would attempt to ping 192.168.1.1 (Or whatever entered).
Suppose that you have already a text file named : IP_List.txt with this contents :
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
192.168.1.15
192.168.1.16
192.168.1.17
192.168.1.18
192.168.1.19
192.168.1.20
www.google.com
www.stackoverflow.com
You can give a try for this batch file : MultiPingTester.bat
#echo off
Title Multi-Ping hosts Tester with colors by Hackoo 2016
call :init
set "MyFile=IP_List.txt"
If Not exist %MyFile% goto error
mode con cols=65 lines=30
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
echo(
call :color 0E " ------- Ping status of targets hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%MyFile%") do (
ping -n 1 %%a | find "TTL=" >nul
if errorlevel 1 (
call :color 0C " Host %%a not reachable KO" 1 & echo Host %%a not reachable KO >>%LogFile%
) else (
call :color 0A " Host %%a reachable OK" 1 & echo Host %%a reachable OK >>%LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
::*************************************************************************************
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::*************************************************************************************
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::*************************************************************************************
:error
mode con cols=70 lines=3
color 0C
cls
echo(
echo ATTENTION !!! Check if the file "%MyFile%" exist !
pause>nul & exit
::*************************************************************************************
Related
How to get pc mac address and restart PC if mac is not on the list.txt?, i only have this getting mac command,
for /f "tokens=3 delims=," %%a in ('"getmac /v /fo csv | findstr Ethernet"') do set MAC=%%a
echo MAC address of this computer is %MAC%
You use getmac and pipe the result through findstr to filter on the required network adaptor.
You store the result into a variable ThisPCMAC
You use the type command to get the content of the list.txt file piped through findstr to filter on ThisPCMAC.
You store the result into a variable FoundMAC.
If FoundMAC is defined you goto :norestart
If FoundMAC is not defined you goto :restart
In :restart, you call shutdown /r with the required additional params
If mistaken, you can call shutdown /a in the allotted time (10 minutes here, see /t 600).
For further help, see shutdown /?
The 2 files should be in the same directory.
Example content of list.txt:
FF-AA-BB-CC-DD-FA
FF-AA-BB-CC-DD-FB
FF-AA-BB-CC-DD-FC
Content of RestartIfThisPCMACnotInList.bat:
#echo off
set ScriptPath=%~dp0
set ThisPCMAC=
set FoundMAC=
echo.
echo ScriptPath = %ScriptPath%
for /f "tokens=3 delims=," %%a in ('"getmac /v /fo csv | findstr Ethernet"') do set ThisPCMAC=%%a
echo.
echo MAC address of this computer is %ThisPCMAC%
for /F "usebackq delims==" %%b in (`"type %ScriptPath%list.txt | findstr %ThisPCMAC%"`) do set FoundMAC=%%b
if DEFINED FoundMAC (
goto :norestart
) else (
goto :restart
)
:norestart
echo.
echo Found %FoundMAC% in %ScriptPath%list.txt: Nothing to do.
goto :end
:restart
echo.
echo %ThisPCMAC% not found in %ScriptPath%list.txt: Restarting...
echo.
echo shutdown /r /f /t 600 /d p:00:00
shutdown /r /f /t 600 /d p:00:00
echo.
echo Cancel restart with the following command:
echo shutdown /a
goto :end
:end
echo.
echo %~fp0 ended.
pause
Example output for :norestart:
C:\test\>RestartIfThisPCMACnotInList.bat
ScriptPath = C:\test\
MAC address of this computer is "FF-AA-BB-CC-DD-FA"
Found FF-AA-BB-CC-DD-FA in C:\test\list.txt: Nothing to do.
C:\test\RestartIfThisPCMACnotInList.bat ended.
Press any key to continue . . .
Example output for :restart:
C:\test\>RestartIfThisPCMACnotInList.bat
ScriptPath = C:\test\
MAC address of this computer is "FF-AA-BB-CC-DD-FD"
"FF-AA-BB-CC-DD-FD" not found in C:\test\list.txt: Restarting...
shutdown /r /f /t 600 /d p:00:00
Cancel restart with the following command:
shutdown /a
C:\test\RestartIfThisPCMACnotInList.bat ended.
Press any key to continue . . .
For the program I am currently working on I am taking a value, which is a proxy in ip:port format, I need to be able to split the ip and port to different variables so that a different program that needs ip and port separate will be able to work. The program is basically an automated ip/proxy switcher for minecraft, just for in game reasons, I have all the code working except for the part that actually changed the proxy. I am not getting any error message, only that I don't actually know what code to write. Anyways, here is my code.
#echo off
color b
title minecraft proxy switcher
set nLine=0
echo input full path to text file containing proxies
set /P "filepath=>"
echo end >> %filepath%
:top
cls
set /A nLine=%nLine%+1
echo now at proxy number %nLine%
CALL :ReadNthLine "%filepath%" %nLine%
PAUSE >NUL & goto:top
GOTO :EOF
::***************************************************************************************
:ReadNthLine File nLine
FOR /F %%A IN ('^<"%~1" FIND /C /V ""') DO IF %2 GTR %%A (ECHO Error: No such line %2. 1>&2 & EXIT /b 1)
FOR /F "tokens=1* delims=]" %%A IN ('^<"%~1" FIND /N /V "" ^| FINDSTR /B /C:"[%2]"') DO set http_proxy=%%B
goto finish
::***************************************************************************************
:finish
if %http_proxy%==end (
cls
echo all proxies have been used
echo will return to top of list in 5 seconds
TIMEOUT /T 5 /NOBREAK
set nLine=0
goto top
)
java -DsocksProxyHost=ip -DsocksProxyPort=port -Xmx800m -jar MinecraftLauncher.exe
echo New ip is %http_proxy%
echo waiting for user input
echo press any key for a new ip
pause
goto top
Any help is greatly appreciated, also if you notice something else that's badly written or incorrect in my code please tell me.
split the string with a for, using proper tokens and delimiters:
set "line=192.168.1.1:8080"
for /f "tokens=1,2 delims=:" %%a in ("%line%") do (
set server=%%a
set port=%%b
)
echo Server %server% Port %port%
here is a basic code skeleton which processes the file line after line (your way works, but this is way easier):
#echo off
set /p "filepath=File: "
:top
set n=0
for /f "tokens=1,2 delims=:" %%a in (%filepath%) do call :process %%a %%b
timeout 5
goto :top
:process
echo trying %n%
set /a n+=1
echo host: %1
echo port: %2
pause
goto :eof
I'm pretty new to this so please bear with me, and if you require anymore information from me please say. Thanks in advance for your help.
I have this code that pings different PCs then returns back if they are online/offline. I wanted to know if you could add another column once the bat file has ran its ping test so it has the computer name next to it.
#echo off
if exist C:\tools\computers.txt goto Label1
echo.
echo Cannot find C:\tools\computers.txt
echo.
Pause
goto :eof
:Label1
echo PingTest executed on %date% at %time% > C:\tools\z.txt
echo ================================================= >> C:\tools\z.txt
for /f %%i in (C:\tools\computers.txt) do call :Sub %%i notepad C:\tools\z.txt
goto :eof
:Sub
echo Testing %1 set state=alive ping -n 1 %1 | find /i "bytes=" || set state=dead echo %1 is %state% >> C:\tools\z.txt
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
99.1.82.28 is alive
99.1.82.100 is alive
ect.
If possible I would like the bat file to run so it displays this;
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
Computer 1 : 99.1.82.28 is alive
Computer 2 : 99.1.82.100 is alive
ect.
--
Would appreciate any help & guidance on this.
Thanks.
You can try this solution :
#echo off
Title Ping Test
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a : !ip! ALive ok" || set "msg=%%a : !ip! Dead failed to respond"
echo !msg!
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
EDIT : on 29/07/2016 # 12:48
Another version with multi-colors : Special thanks goes to ICARUS for the color function (-_°)
#echo off
Rem Special thanks goes to Iracus for the color function (-_°)
mode con cols=60 lines=20
Title Multi-Ping hosts Tester with Multi-colors by Hackoo
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
call :init
echo(
call :color 0E "------- Ping Status of Computers hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a - !ip! ALive ok" && Call :Color 0A "!msg!" 1 || set "msg=%%a - !ip! Dead failed to respond" && Call :Color 0C "!msg!" 1
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
EDIT : Update On 23/08/2016
http://pastebin.com/zjYwSqUM
I wrote a windows batch script to check and move files to another directory based on the list I put in a notepad file named list.txt. But I have no idea that how to set the while-loop. Only to jump out of the subroute when the condition fulfill.
In C Programming, we could write like this by setting a while-loop direcly. But seems in windows batch is quite different.
All I want is like this:
Directory A:
1. A.txt
2. B.txt
3. list.txt (By line sequential with filename want to move)
4. process.bat
Directory B:
None of files (Then move a file by order of line set in list.txt) OR
A.txt (If already existed a text file in directory, process.bat will pause before A.txt disappear)
Process.bat
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
if exist D:\DirectoryA\*.txt (
echo %time% >> D:\AutoLog\Log.txt
echo Previous job did not finished yet. >> D:\AutoLog\Log.txt
Timeout /t 30
echo.
)
set name=%*
if exist %name%.txt (
echo %time% >> D:\AutoLog\Log.txt
echo File found and processing %name%.txt now... >> D:\AutoLog\Log.txt
copy "%~dp0\%name%.txt" "D:\DirectoryB"
echo Transfer %name%.txt completed!! >> D:\AutoLog\Log.txt
echo. >> D:\AutoLog\Log.txt
Timeout /t 790
echo.
echo ==============================================================
)
:eof
Please guide me to finish the script by using a while-loop method. Thanks
I change some script sequence and it works now.
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
set name=%*
if exist C:\Test2\*.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo Previous job did not finished yet. >> C:\Test2\Log.txt
Timeout /t 5
echo.
echo. >> C:\Test2\Log.txt
goto :processline
)
if exist %name%.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo File found and processing %name%.txt now... >> C:\Test2\Log.txt
copy "%~dp0\%name%.txt" "C:\Test2"
echo Transfer %name%.txt completed!! >> C:\Test2\Log.txt
echo. >> C:\Test2\Log.txt
Timeout /t 10
echo.
echo ==============================================================
)
:eof
This will copy as well as count the number of lines from your text file..
# echo off
:TextPath
cls
set /p Input=#1 Enter the full path of the text file :
set /p Source=#2 Enter the full path of Source :
set /p Target=#3 Enter the full path of Destination :
:choice
set /P c=Ready to Continue[Y/N]?
if /I "%c%" EQU "Y" goto :Yes
if /I "%c%" EQU "N" goto :No
goto :choice
:Yes_Local
for /f "delims=" %%i in (%Input%) do echo f| xcopy /f /y "%Source%\%%i" "%Target%\%%i"
for /f %%C in ('Find /V /C "" ^< %Input%') do set Count=%%C
msg * No of Lines executed= %Count%
exit
:No
cls
color e
echo Redirecting to Main....
PING 127.0.0.1 -n 2 >NUL
cls
echo Please wait
PING 127.0.0.1 -n 4 >NUL
goto TextPath
I am currently trying to ping a list of hostnames, preferably one at a time, and then use nslookup on that hostname. If the hostname in nslookup matches up with the hostname first used, then I would like to use the IP to check against another file (called home.txt) that would contain the location.
What I have so far:
#Echo Off
If '%1'=='' GOTO Syntax
Echo Running Script and Saving Results to Results.CSV
Echo Script Run %date% %time% >> Results.csv
For /F %%i in (%1) do Call :StartPing %%i
Goto :eof
:StartPing
PING %1 -n 1 | FIND /i "TTL" > nul && goto Success
PING %1 -n 1 | FIND /i "timed" > nul && goto Timedout
PING %1 -n 1 -w 400 | FIND /i "TTL" > nul || goto ErrorMsg
:Success
for /F "tokens=3" %%a in ('ping %1 ^| find /i "TTL"') do set Address=%%a
for /F "tokens=2" %%a in ('ping -a %Address::=% ^| find /i "pinging"') do set HostName=%%a
set IPAddress=%Address::=%
echo %1, %IPAddress%,%Hostname%
echo %1, %IPAddress%,%Hostname% >> Results.csv
NSLOOKUP %IPAddress% | FIND /i "Name" = "%Hostname%" goto home
:home
echo %IPAddress% home.txt
Goto :EOF
:Timedout
Echo %1, Request timed out.
Echo %1, Request timed out. >> Results.csv
:ErrorMsg
Echo %1, Ping request could not find host.
Echo %1, Ping request could not find host. >> Results.csv
goto :eof
:Syntax
echo . . .
goto :eof
An example of what home.txt might contain:
10.102.6.43 = 2J
IE, just a bunch of IP ranges mapped to office locations.
Ideally, the script should then make a popup box showing the location of the IP address, or just echo it on-screen.
Any ideas?
Made some changes and tested a few things, here is what i have so far.
#echo Off
#cls
if '%1'=='' GOTO Syntax
echo Running Script and Saving Results to Results.CSV
echo Script Run %date% %time% >> Results.csv
for /F %%i in (%1) do Call :StartPing %%i
goto :EOF
:StartPing
PING %1 -n 1| FIND /i "TTL" > nul && goto Success
PING %1 -n 1| FIND /i "timed" > nul && goto Timedout
PING %1 -n 1 -w 400 | FIND /i "TTL" > nul || goto ErrorMsg
:Success
for /F "tokens=3" %%a in ('ping %1 ^| find /i "TTL"') do set Address=%%a
for /F "tokens=2" %%a in ('ping -a %Address::=% ^| find /i "pinging"') do set HostName=%%a
set IPAddress=%Address::=%
for /f "tokens=2" %%b in ('nslookup %IPAddress%^|find /i "Name"') do set fqdn=%%b
echo %1, %IPAddress%,%Hostname%
echo %1, %IPAddress%,%Hostname% >> Results.csv
goto :EOF
:Timedout
Echo %1, Request timed out.
Echo %1, Request timed out. >> Results.csv
:ErrorMsg
Echo %1, Ping request could not find host.
Echo %1, Ping request could not find host. >> Results.csv
goto :EOF
:Syntax
echo . . .
goto :EOF
:EOF
echo this is the END OF FILE
pause
Every time I run hh.bat host.txt, everything runs fine until it hits the nslookup part, then it creates between 1500 and 3000 processes in windows task manager. without the NSLOOKUP part hh.bat works fine.
I had the nslookup part in a separate script called nslookup.bat which worked fine for a little while, and now it does not want to work. create that amount of processes everytime...
testing in a Hyper-V environment with 3 windows 7 pcs and a DC.