Add "if arguement" against a Pipe for a variable - windows

I'm new at writing code and batch files. I'm trying to automate a user setup by allowing the user to issue the following batch file:
Command Executed = "BVT_AudioDecode_Setup.bat V:\WP\BVT\Audio\Decode 10.42.233.237"
#echo off
::Conditions leading to errors if the batch script is not executed correctly
if "%1"=="" and "%2"=="" goto error1
if "%1"=="" goto error2
if "%2"=="" goto error3
::Allows user to set the "Source Path" to copy the testcase files from
set source=%1
::Allows user to set the "Destination Path" to copy the testcase files from
set IP_Address=%2
::Tells the user what the "Source" and "Destination" Paths are
echo Source Path = %1
echo Destination Path = %2
echo.
powershell.exe -File "bat_script.ps1" %1 %2 -NoProfile -NoExit
goto end
:error1
echo.
echo Error Syntax: BVT_AudioDecode_Setup.bat "Source_Path\AudioDecode_Testcase_Folder" "Device IP Address"
echo.
echo For example: BVT_AudioDecode_Setup.bat V:\WP\BVT\Audio\Decode 10.42.233.237
echo -or-
echo BVT_AudioDecode_Setup.bat C:\WP\BVT\Audio\Decode 10.42.233.237
echo.
echo.
goto end
:error2
echo.
echo Error Syntax: BVT_AudioDecode_Setup.bat "Source_Path\AudioDecode_Testcase_Folder" "Device IP Address"
echo.
echo For example: BVT_AudioDecode_Setup.bat V:\WP\BVT\Audio\Decode 10.42.233.237
echo -or-
echo BVT_AudioDecode_Setup.bat C:\WP\BVT\Audio\Decode 10.42.233.237
echo.
echo.
goto end
:error3
echo.
echo Error Syntax: BVT_AudioDecode_Setup.bat "Source_Path\AudioDecode_Testcase_Folder" "Device IP Address"
echo.
echo For example: BVT_AudioDecode_Setup.bat V:\WP\BVT\Audio\Decode 10.42.233.237
echo -or-
echo BVT_AudioDecode_Setup.bat C:\WP\BVT\Audio\Decode 10.42.233.237
echo.
echo.
goto end
:end
This was tested and it works.
Now I am trying to add/test a simple block of code, but I cannot find the correct syntax. Yes, I have been googling for the last 3 hours. Here is what I am trying to do:
Command Executed = "Random.bat C:\Users"
Command Executed = "Random.bat C:\InvalidDirectory"
::Conditions leading to errors if the batch script is not executed correctly
#ECHO OFF
SET "mypath=%1"
ECHO %mypath%
cd %mypath% | find "%invalidpath%"
Echo %invalidpath%
If "%invalidpath%=The system cannot find the path specified." (
goto error1)
else (
goto BeginTest)
::Begins the testcase
:BeginTest
::Do some stuff
goto end
:error1
echo Error: Invalid Path
goto end
:end
If anyone could point me in the right direction it would be much appreciated...

You can use the IF EXIST statement to check for the presence of a directory. For example, to test for C:\WIN and then change to C:\WIN if it exists :
C:
IF NOT EXIST "C:\WIN\." GOTO NOWINDIR
CD \WIN
:NOWINDIR

because the "not-found-answer" from "cd xxxx" will vary with the language of your windows-installation you should prefer a language-independent solution.
Use %errrorlevel% for that.
cd c:\existingpath\ will return an errorlevel of "0"
cd c:\notexistingpath\ will return "1"
so a good solution would be:
SET "mypath=%1"
ECHO %mypath%
cd %mypath%
If %errorlevel%=0 goto BeginTest else goto error1
...

It worked, thanks. Here is what I have in case anyone else runs into this problem:
::Conditions leading to errors if the batch script is not executed correctly
#ECHO OFF
SET "source=%1"
ECHO %source%
IF NOT EXIST "%source%" goto error1
ECHO Directory Exists
cd %source%
goto end
:error1
echo Error: Invalid Path
goto end
:end
Now I need an if condition for a true IP Address
::Conditions leading to errors if the batch script is not executed correctly
#ECHO OFF
SET "IP_Address=%1"
ECHO %IP_Address%
::Checks if the IP Address is valid
IF NOT EXIST "%IP_Address%" goto error2
ECHO Directory Exists
goto end
:error1
echo.
echo Error: Invalid Path
echo %source%
goto end
:error2
echo.
echo Error: Invalid IP Address
echo %IP_Address%
goto end
:end
It automatically checks to see if the IP Address is a path. I could add a "\\" in front of the "IF NOT EXIST "\\%IP_Address%" goto error2", but the issue with this is that the computer will not be able to connect to the device unless it uses either telnet, or "Open-Device" command through powershell. It can however ping that IP Address.
Is there is a way to setup to read a successful ping vs unsuccessful ping??

same solution with %errorlevel%
ping -n 1 -w 100 %ip-address%
if %errorlevel%=0 then goto doesexist else goto cannotreach
...
All commands will return an errorlevel. Normally Zero, if all was ok, and a non-zero- value for errors.

It's still not working correctly with the IP address listing, but I am closer with your help. Here is what I have when I execute the bat with a valid IP Address to ping:
::Conditions leading to errors if the batch script is not executed correctly
#ECHO OFF
SET IP_Address=%1
ECHO %IP_Address%
::Checks if the IP Address is valid
ping -n 1 -w 1000 %IP_Address%
if not "%errorlevel%=0" goto error2
goto end
:error2
echo.
echo Error: Invalid IP Address
echo %IP_Address%
goto end
:end
Upon execution this is what I am seeing in cmd:
c:\>Random.bat 192.168.1.46
192.168.1.46
Pinging 192.168.1.46 with 32 bytes of data:
Reply from 192.168.1.46: bytes=32 time=1ms TTL=128
Ping statistics for 192.168.1.46:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 1ms, Maximum = 1ms, Average = 1ms
goto was unexpected at this time.
Once this is solved, I would also like to know a way to hide the output:
Pinging 192.168.1.46 with 32 bytes of data:
Reply from 192.168.1.46: bytes=32 time=1ms TTL=128
Ping statistics for 192.168.1.46:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 1ms, Maximum = 1ms, Average = 1ms

to hide the output use >nul
ping -n 1 -w 1000 %IP_Address% 1>nul 2>nul
1>nul will send the "normal" output to nirvana
2>nul will send the errormessages to nirvana
So if you use " 1>nul" (or just " >nul") you will have the errormessage on the screen, but not the "reply", "statistics" and that kind of stuff.
I don't understand the "unexpected goto" just now - I will have a look on that tomorrow.

Ah I finally found it after looking up usage for errorlevel
::Conditions leading to errors if the batch script is not executed correctly
#ECHO OFF
SET IP_Address=%1
ECHO %IP_Address%
::Checks if the IP Address is valid
ping -n 1 -w 100 %IP_Address% 1>nul
if "%errorlevel%"=="1" goto error2
:error2
echo.
echo Error: Invalid IP Address
echo %IP_Address%
goto end
:end
Thanks for the help everyone.

Related

Batch File Resume with Prewritten Arguments

I have two batch files one batch files calls another. The one that calls the other is called install.bat, and the other controller.bat.
The contents of install.bat are as follows:
start controller.bat a.exe b.exe
Then the controller.bat file operates as such:
#echo off
:: Check if the first argument is passed
if "%~1"=="" (
echo "No first argument passed"
) else (
set first_arg=%~1
)
:: Check if the second argument is passed
if "%~2"=="" (
echo "No second argument passed"
) else (
set second_arg=%~2
if not "%~1" == "" (
set current=one
) else(
echo twob >%~dp0current.txt
)
)
call :Resume
goto %current%
goto :eof
:one
::Add script to Run key
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /d %~dpnx0 /f
echo two >%~dp0current.txt
echo -- Section one --
echo "update will start"
start /wait %second_arg%
echo "update done"
pause
shutdown -r -t 0
goto :eof
:two
echo three >%~dp0current.txt
echo -- Section two --
echo "updating now"
Start /wait %first_arg%
echo "Update Finish"
pause
shutdown -r -t 0
goto :eof
:twob
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /d %~dpnx0 /f
echo three >%~dp0current.txt
echo -- Section two --
echo "updating now"
Start /wait %first_arg%
echo "Update Finish"
pause
shutdown -r -t 0
goto :eof
:three
::Remove script from Run key
reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /f
del %~dp0current.txt
echo -- Section three --
pause
goto :eof
:resume
if exist %~dp0current.txt (
set /p current=<%~dp0current.txt
) else (
set current=one
)
The problem it is not working well it jumps into twob and then straight to three. It is supposed to show the intermediate steps to a user to show the updates are occurring.
I am expecting it to be able to read if one argument is supplied let's say the second and not the first and still do the jumps to right labels. Right now, the labels are a bit mixed up when I supply both args %~1 and %~2.

Batch file to ping and display different output

I'm trying to create a batch file to ping a few devices to output a .txt that shows the results.
ping -n 1 router | find "TTL" > nul
IF errorlevel 1 (
echo "Cannot ping" > DIRECTORY
)
ELSE (
echo "Ping success" > DIRECTORY
)
Currently I can only show whether it succeeds or fails. However I'm thinking if there is a way to differentiate between how it fails e.g. request time out VS host unreachable.
Does anyone know how I can tweak it?
EDIT:
#echo off
for /f "delims=" %%i in ('ping -n 2 router ^| findstr "Reply timed Hardware"') do set "res=%%~i"
if not "%res:timed=%" == "%res%" echo "Time out" > C:\Users\eddie\Desktop\results\timeout.txt
if not "%res:unreachable=unreachable%" == "%res%" echo "Destination host is unreachable" > C:\Users\eddie\Desktop\results\unreach.txt
if not "%res:Reply=%" == "%res%" echo "successful ping" > C:\Users\eddie\Desktop\results\success.txt
pause
Here is an untested example, I cannot test this now because I am not able to setup any routing that will create various results such as Destination host unreachable which comes from the router:
#echo off
set "host=router"
for /f "delims=" %%i in ('ping -n 2 %host% ^| findstr "TTL timed request unreachable"') do set "res=%%~i"
if not "%res:timed=%" == "%res%" (echo Time out)>"%userprofile%\Desktop\timeout.txt"
if not "%res:request=%" == "%res%" (echo Unknown Host)>"%userprofile%\Desktop\unknownhost.txt"
if not "%res:unreachable=unreachable%" == "%res%" (echo Destination host is unreachable)>"%userprofile%\Desktop\unreach.txt"
if not "%res:TTL=%" == "%res%" (echo Successful ping)>"%userprofile%\Desktop\success.txt"
The concept is simply, the findstr will capture only results from any of Reply or timed or hardware. We then just test if the string contains a substring and echo accordingly.
The second option in the list to capture unreachable has the & goto :EOF option simply because it will contain either just destination host unreachable or Reply from ... : Destination host unreachable like the below screenshot. We do not want to create both messages for Unreachable and Reply (which comes from the Router).

If statement in batch file - user chooses option

New to batch/sql files. Thanks for you help.
What im trying to do:
user picks option 1, runs my sql file.
user picks 2, exits program.
user enters nothing or invalid option, ECHO "invalid option".
Problem: anything I type will exit my program. What am I doing wrong?
ECHO 1 - Show Report
ECHO 2 - Exit
SET choice=""
SET /P input=Your choice:
IF "%input%"=="1" (
GOTO :sql file
) ELSE (
IF "%input%"=="2" (
GOTO :Exit
)
) ELSE (
IF "%input%"=="" (
ECHO Invalid option chosen.
)
)
PAUSE
Just use the choice command, its instructions are available by entering choice /? at the Command Prompt.
#ECHO OFF
ECHO 1 - Show Report
ECHO 2 - Exit
CHOICE /C 12 /M "Your choice"
IF ERRORLEVEL 2 GOTO :EOF
REM This line is your SQL report code
PAUSE
If you still wanted to use, what in your case I believe is the wrong Set /P input method, then something like this should be relatively robust, given that your end user is free to enter whatever they like as input, mischievous or harmful intent included:
#ECHO OFF
ECHO 1 - Show Report
ECHO 2 - Exit
:GETInput
SET "input="
SET /P "input=Your choice: "
2>&1 SET input | FINDSTR /XR "input=[12]" 1>NUL || (
ECHO Invalid option chosen
GOTO GETInput
)
IF %input% EQU 2 GOTO :EOF
REM This line is your SQL report code
PAUSE
There is one extract closing bracket [Line #12] inside nested if..else. Also, as far as i know, your label :sql file should not contain space and you must declare it inside the batch file (Same for label :Exit)
I did few changes in your code to make it work
#echo off
:Main
cls
ECHO 1 - Show Report
ECHO 2 - Exit
SET choice=""
SET /P input=Your choice:
IF "%input%"=="1" (
GOTO :SQLReport
) ELSE IF "%input%"=="2" (
GOTO :EOF
) ELSE (
ECHO.
ECHO Invalid option chosen.
pause
GOTO :Main
)
:SQLReport
ECHO.
ECHO Running SQL Report...
GOTO :EOF
:EOF

Windows batch file to block multiple hosts (using list)

I want to add multiple lines to the hosts file if they're not existing. My code works great but I want to do it for a list of 30 entries and thats where I don't know how to handle it. I thought about a list and a for-loop but I don't know how.
#ECHO OFF
ECHO Checking administrator right.
OPENFILES >NUL 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator right detected.
ECHO.
ECHO Hosts file : %WINDIR%\system32\drivers\etc\hosts
ECHO.
SETLOCAL ENABLEDELAYEDEXPANSION
SET BLOCKLINE=127.0.0.1 example.com
ECHO Checking : !BLOCKLINE!
FIND /C /I "!BLOCKLINE!" "%WINDIR%\system32\drivers\etc\hosts" >NUL 2>NUL
IF !ERRORLEVEL! NEQ 0 (
ECHO Line not found, adding to the hosts file.
ECHO !BLOCKLINE!>>%WINDIR%\system32\drivers\etc\hosts
) ELSE (
ECHO Line found.
)
ECHO.
ENDLOCAL
ECHO Patching is completed.
ECHO Check hosts file if you want to see the result.
ECHO.
) ELSE (
ECHO Administrator right not detected.
ECHO You need admin right to use this hosts patch!
ECHO.
)
PAUSE
A basic for loop will suffice.
Define the lines to test in the loop set
For %%L in (
"127.0.0.1 example1"
"127.0.0.30 example30"
) Do (
ECHO Checking : %%~L
FIND /C /I "%%~L" "%WINDIR%\system32\drivers\etc\hosts" >NUL 2>NUL
IF !ERRORLEVEL! NEQ 0 (
ECHO Line not found, adding to the hosts file.
>>"%WINDIR%\system32\drivers\etc\hosts" ECHO %%~L
) ELSE (
ECHO Line found.
)
)

Inputting space in prompts crash batch file

I am trying to do a command line replica compeletely out of boredom and I have an issue. Here is my code:
#echo off
set /a secret=1
color B
title Subnet Access v1.0
echo ____________________________________________________________
echo / I
echo I Subnet Access v1.0 I
echo I____________________________________________________________/
echo.
echo.
timeout 3 > NUL
echo sys rev init
timeout 1 >NUL
echo loading keyframes
echo please wait
timeout 5 >NUL
echo.
echo.
echo Checking for alerts
timeout 6 >NUL
echo alert 0-21-77
timeout 1 >NUL
echo.
set /p pid=enter pid: || set pid=empty
IF "%pid%"=="1123321231" (
echo.
set /a "secret+=1"
cls
echo Secrets %secret%/10 found.
timeout 3 >NUL
cls
echo.
echo pid confirmed
timeout 1 >NUL
echo checking with server...
timeout 5 >NUL
cls
color C
echo COULD NOT IDENTIFY
timeout 1 >NUL
cls
echo.
timeout 1 >NUL
cls
echo COULD NOT IDENTIFY
timeout 1 >NUL
cls
echo.
timeout 1 >NUL
cls
echo COULD NOT IDENTIFY
timeout 1 >NUL
cls
echo.
timeout 1 >NUL
goto :unidentify
)
IF NOT "%pid%"=="1123321231" GOTO :unidentify
:unidentify
cls
echo.
echo unauthorized access
timeout 3 >NUL
echo level drop
timeout 1 >NUL
echo dropping...
timeout 3 >NUL
echo level now 0
timeout 4 >NUL
echo sys exit
timeout 1 >NUL
cls
cls
set su=0
color 7
title sys/rev/console-override
echo Subnet Console v0.1
echo Made by Murtaugh
echo.
:sub01 ::PROBLEM STARTS HERE
IF %su%==0 (
set /p commandMur=sys/dev/: #^> || set commandMur=emptycom
)
IF %su%==1 (
color B
set /p commandMur=sys/dev/: $^> || set commandMur=emptycom
)
IF %commandMur%==help (
::help segment
echo.
echo Help v0.1 Alpha by Murtaugh
echo.
echo Commands are listed below:
echo dir - Lists your directory's contents.
echo help - Shows this page.
echo connect - Connects you to an IP address.
echo.
goto :sub01
)
IF "%commandMur%"=="exit" (
goto :eof
)
IF "%commandMur%"=="cls" (
cls
goto :sub01
)
IF "%commandMur%"=="su" IF "%su%"=="0" (
cls
echo.
set /a "secret+=1"
echo Secrets %secret%/10 found.
set su=1
goto :sub01
)
IF "%commandMur%"=="su" IF "%su%"=="1" (
goto :sub01
)
IF "%commandMur%"=="emptycom" (
goto :sub01
)
IF NOT "%commandMur%"=="exit" IF NOT "%commandMur%"=="help" IF NOT "%commandMur%"=="cls" IF NOT "%commandMur%"=="su" (
echo "%commandMur%": Bad command or file name
echo.
goto :sub01
) ::PROBLEM ENDS HERE
But when I input something with spaces it says test==exit was unexpected at this time. and just close. Is there anyway I can fix this? Thanks.
EDIT: Tried "%prompt%"=="test" thing, doesn't work.
test==exit was unexpected ... is a typical syntax error with if (set doesn't give this type of error).
Most likely you have a if %command%==exit ...-command the next line. To avoid the syntax error, write if "%command%"=="exit" ...
im not really a great programmer, but try adding "QUOTATION TAGS" when you type text with spaces, beacuse batch sometimes get confused about those spaces

Resources