I have this assignment from my teacher in regards to creating a batch file that does something. its pretty huge assignment, but one part i stuck. it asks:
If the value of the userdomain variable is equal to the value of the computername variable then
Store into a file called output.txt the following information:
1. The current username
2. The current computername
So im thinking, my username(domain username) would never be same as a computer name anywhere in the world! lol
So that would NEVER happen! in this case i should do nothing!
So im confused. What am i missing?!
It is possible to give the computer the name of the user account in a domain. That is not forbidden. That your computer has a different name than your user account in domain or locally does not mean it is not possible.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
:RunNameCompare
if /I "%COMPUTERNAME%" == "%USERNAME%" (
setlocal EnableDelayedExpansion
echo User name: !USERNAME!>output.txt
echo Computer name: !COMPUTERNAME!>>output.txt
endlocal
) else (
echo/
echo Computer name and user account name are different.
echo/
%SystemRoot%\System32\choice.exe /N /M "Simulate identical names [Y/N]: "
if not errorlevel 2 set "COMPUTERNAME=%USERNAME%" & goto RunNameCompare
)
endlocal
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
See also the following pages and articles:
Wikipedia article about Windows Environment Variables
Microsoft article about Using Command Redirection Operators
Microsoft article about Testing for a Specific Error Level in Batch Files
Single line with multiple commands using Windows batch file
This answer for details about the commands SETLOCAL and ENDLOCAL
DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
The outer SETLOCAL and ENDLOCAL are used to create a local environment on running this batch file so that even after taking the simulate identical names option, the predefined environment variable COMPUTERNAME has its original value after running the batch file from within a command prompt window as recommended on debugging and verifying a batch file in development.
The inner SETLOCAL and ENDLOCAL are used to be able to output correct into file output.txt even computer and user account names containing command line critical characters like &()[]{}^=;!'+,`~|<> or ending with a space and a number in range 1 to 9 without enclosing both names in double quotes.
Related
I am currently making password protected batch file,
and the problem is when I type #echo on or %#echo on% it shows the password, (one moment, but if you do video you can see it clearly).
When I changed 3rd line to this if "%pwd%"==somepassword, then by typing #echo on again shows the password.
I have some few ideas. For ex. make #echo off unchangeable, or character escaping, but I am not that good at batch scripting so I can't write it by code.
Is there anyone who can help me with this?
#echo off
set /p pwd="Enter password: "
if %pwd%==somepassword (cmd /k) else (exit)
There could be used:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "pwd="
:PwdPrompt
set /P "pwd=Enter password: " || goto PwdPrompt
setlocal EnableDelayedExpansion
if not "!pwd!" == "somepassword" exit /B
endlocal
echo The password is correct!
echo/
pause
endlocal
There is first defined the required execution environment completely with
turning off command echo mode and
enabling command extensions and
disabling delayed variable expansion.
The environment variable pwd is next explicitly undefined. The user must enter a password.
The user is prompted for the password and this is done in a loop as long as the user does not enter a string at all. So no input is not accepted by the batch file.
Then delayed variable expansion is enabled before doing the string comparison with making use of delayed variable expansion to prevent a modification of the batch file code for execution by the string input by the user.
If the two compared strings are not equal, the batch file processing (not necessarily the command process) is exited which results in implicit execution of endlocal twice by cmd.exe for the two setlocal before really exiting the processing of the batch file.
Otherwise on input password string being equal the password string in the batch file the previous local environment with disabled delayed expansion is restored before the batch file processing is continued with the next commands.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
goto /?
if /?
pause /?
set /?
setlocal /?
I strongly recommend to read also:
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
It explains in full details why this code is fail-safe and secure.
Single line with multiple commands using Windows batch file
It explains in full details the meaning of the command operator ||.
Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files
It explains in full details how a string comparison is done with command IF.
How to pass environment variables as parameters by reference to another batch file?
It explains in full details the commands SETLOCAL and ENDLOCAL.
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
This is my code:
set /p name=user save name
if %name%==[""]
cd c:\users\student\desktop\login system\usersXD
echo set "name=%name%"> %name%.bat
My code is not working. and i will like to load them up to view
I suggest following code for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
goto PromptName
:ErrorInvalid
echo/
echo Error: The character !InvalidChar! is not allowed in name.
echo/
endlocal
:PromptName
set "Name="
set /P "Name=User save name: "
rem Has the user not input anything?
if not defined Name goto PromptName
rem Remove all double quotes from input string.
set "Name=%Name:"=%"
rem Has the user input just double quotes?
if not defined Name goto PromptName
rem Check if the input string contains any character not allowed in a file name.
setlocal EnableDelayedExpansion
for %%I in ("<" ">" ":" "/" "\" "|") do if not "!Name:%%~I=!" == "!Name!" set "InvalidChar=%%~I" & goto ErrorInvalid
if not "!Name:?=!" == "!Name!" set "InvalidChar=?" & goto ErrorInvalid
if not "!Name:**=!" == "!Name!" set "InvalidChar=*" & goto ErrorInvalid
endlocal
cd /D "%UserProfile%\Desktop\login system\usersXD"
echo set "Name=%Name%">"%Name%.bat"
endlocal
The file name of the batch file to create must be enclosed in double quotes because it could contain a space or one of these characters &()[]{}^=;!'+,`~ which require enclosing the file name in double quotes.
This batch file should not be stored in directory %UserProfile%\Desktop\login system\usersXD on having file extension .bat as it could be overwritten during execution if the user enters a name the name of the batch file. It would be safe to have this batch file in that directory with file extension .cmd.
The batch file is still not 100% fail-safe despite the checks already added, but the user input string itself cannot result anymore in an exit of batch file execution because of a syntax error.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cd /?
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
See also:
Wikipedia article listing the predefined Windows environment variables like UserProfile
Single line with multiple commands using Windows batch file explaining the operator &
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
Microsoft documentation page Using command redirection operators explaining the redirection operator >
Microsoft documentation page Naming Files, Paths, and Namespaces listing which characters are not allowed in file/folder names
This should work to save a variable in a bat file
If I remember
(
Echo set test=%
Echo set test=%test%
Echo set test=%test%
)>Test.bat
I have a problem when using the loop. What I want to do is to change the file name by adding a number "N" at the end of the file name in each iteration, like file1, file2, file3, ... So it should not overwrite the previous file name.
set path=D:\MeasurementData\%~n0%
echo %path%
pause
for /L %%N in (1,1,5) do (
set file="%path%%%N"
echo %file%
pause
start C:\TomoK.exe %file% "D:\MParameter.mff" "D:\MParameter.mcf"
Pause
)
Does anyone know how to solve this?
My first suggestion is never replacing a predefined environment variable like PATH except there is a very good reason to do it. Open a command prompt window and run set to get output all predefined variables with their current values. Or look on Wikipedia article about environment variables the chapter Windows Environment Variables and read answers on What is the reason for '...' is not recognized as an internal or external command, operable program or batch file?
My second suggestion on needing help it is advisable to open a command prompt window and run each command used in batch file with /? as parameter like set /?. Then the help for the command is output on one or more pages which can be studied. How to use delayed expansion and when it must be used is explained by help of command SET on an IF and a FOR example. Other helpful pages on writing batch files are Microsoft's command-line reference and SS64.com - A-Z index of the Windows CMD command line.
My third suggestion is reading answer on How to set environment variables with spaces? and the other Stack Overflow question linked there. And the second half on this answer with details about the commands SETLOCAL and ENDLOCAL.
After studying all those help and web pages it should be no problem anymore to understand this code:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "DataPath=D:\MeasurementData\%~n0"
for /L %%N in (1,1,5) do (
set "DateFile=%DataPath%%%N"
echo !DateFile!
pause
C:\TomoK.exe "!DateFile!" "D:\MParameter.mff" "D:\MParameter.mcf"
pause
)
endlocal
I don't know why command START was used to run the executable TomoK.exe and therefore removed it.
However, the batch file could be also written without delayed expansion because the environment variable DataFile is not really needed in body of loop at all. And the entire batch code above can be optimized to a single command line in batch file:
#for /L %%N in (1,1,5) do #C:\TomoK.exe "D:\MeasurementData\%~n0%%N" "D:\MParameter.mff" "D:\MParameter.mcf"
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
pause /?
set /?
setlocal /?
start /?
I'm trying to execute a batch file "spoon.bat" from PENTAHO (pdi-ce-7.1.0.0-12), but there is an error.
Part of batch file where the error is found:
if "%SPOON_CONSOLE%"=="1" set PENTAHO_JAVA=C:\Program Files (x86)\Java\jre1.8.0_121\bin\java.exe
if not "%SPOON_CONSOLE%"=="1" set PENTAHO_JAVA=C:\Program Files (x86)\Java\jre1.8.0_121\bin\javaw.exe
set IS64BITJAVA=0
call "%~dp0set-pentaho-env.bat"
But I receive next below error:
The system cannot find the path specified
The error is when I'm trying to assign the path where java.exe or javaw.exe are found to "PENTAHO_JAVA".
I've modified the path with double quote mark, but doesn't work; and also I've modified as:
if "%SPOON_CONSOLE%"=="1" set "PENTAHO_JAVA=C:\<Program Files (x86)>\Java\jre1.8.0_121\bin\java.exe"
Any idea to how declare it to fix it?
Where is the environment variable PENTAHO_JAVA referenced?
It must be referenced with "%PENTAHO_JAVA%" because the string assigned to this environment variable contains characters like a space or &()[]{}^=;!'+,`~. This is explained in help of Windows command interpreter output on running in a command prompt window cmd /? in last paragraph on last help page.
It is of course also possible to define the environment variable with the necessary double quotes already added, i.e. use:
if "%SPOON_CONSOLE%"=="1" set "PENTAHO_JAVA="%ProgramFiles(x86)%\Java\jre1.8.0_121\bin\java.exe""
if not "%SPOON_CONSOLE%"=="1" set "PENTAHO_JAVA="%ProgramFiles(x86)%\Java\jre1.8.0_121\bin\javaw.exe""
set "IS64BITJAVA=0"
call "%~dp0set-pentaho-env.bat"
But this is not recommended. Better would be to use
if "%SPOON_CONSOLE%"=="1" set "PENTAHO_JAVA=%ProgramFiles(x86)%\Java\jre1.8.0_121\bin\java.exe"
if not "%SPOON_CONSOLE%"=="1" set "PENTAHO_JAVA=%ProgramFiles(x86)%\Java\jre1.8.0_121\bin\javaw.exe"
set "IS64BITJAVA=0"
call "%~dp0set-pentaho-env.bat"
and reference environment variable PENTAHO_JAVA enclosed in double quotes where it is necessary to specify its value enclosed in double quotes.
Example:
#echo off
rem Get path of latest installed Java directly from Windows registry.
for /F "skip=1 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\javaws.exe" /v Path 2^>nul') do if /I "%%N" == "Path" set "PENTAHO_JAVA=%%P" & goto JavaPathFound
rem Path of Java not found in registry, search for 32-bit Java in the default
rem program files folders of 64-bit and 32-bit Windows and take first found.
if "%ProgramFiles(x86)%" == "" goto Windows_x86
for /R "%ProgramFiles(x86)%" %%I in (java*.exe) do set "PENTAHO_JAVA=%%~dpI" & goto JavaPathFound
:Windows_x86
for /R "%ProgramFiles%" %%I in (java*.exe) do set "PENTAHO_JAVA=%%~dpI" & goto JavaPathFound
echo Error: Java binary directory not found.
echo/
pause
goto :EOF
:ErrorJavaEXE
echo Error: File %PENTAHO_JAVA% not found.
echo/
pause
goto :EOF
:JavaPathFound
if not "%PENTAHO_JAVA:~-1%" == "\" set "PENTAHO_JAVA=%PENTAHO_JAVA%\"
if "%SPOON_CONSOLE%" == "1" (
set "PENTAHO_JAVA=%PENTAHO_JAVA%java.exe"
) else (
set "PENTAHO_JAVA=%PENTAHO_JAVA%javaw.exe"
)
rem Check existence of Java executable to run.
if not exist "%PENTAHO_JAVA%" goto ErrorJavaEXE
"%PENTAHO_JAVA%" -version
call "%~dp0set-pentaho-env.bat"
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
for /?
goto /?
if /?
pause /?
reg /?
reg query /?
rem /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul whereby redirection operator must be escaped in this batch code on FOR command line with caret character ^. And read answer on Single line with multiple commands using Windows batch file for an explanation of & operator.
Generally, don't modify the shell scripts coming with Kettle. You're supposed to set certain environment variables to adapt the scripts to your runtime environment. Look at the top comment section in script set-pentaho-env to learn what's best for your system.
BTW: The current Java 8 security baseline 8u131 was released in April 2017 - you're way behind that. Also, are you aware of the fact that you are using a 32bit JVM with limited RAM support?
I am new to writing batch files. I want to create a batch file that will allow me to change 2 directories using variables. What I have below is what I have thus far. Any ideas?
#echo off
S:
cd AAA
set /p CLIENTCODE=CLIENTCODE?
cd %CLIENTCODE%
pause
set /p SCHEMANAME=SCHEMANAME?
cd %SCHEMANAME%
pause
Try following batch code:
#echo off
setlocal
set "ClientCode=AAA"
set "SchemaName=5H"
:UserPrompt
cls
set /P "ClientCode=Enter client code (default: %ClientCode%): "
set /P "SchemaName=Enter schema name (default: %SchemaName%): "
if not exist "S:\%ClientCode%\%ClientCode%%SchemaName%" goto InputError
cd /D "S:\%ClientCode%\%ClientCode%%SchemaName%"
endlocal
goto :EOF
:InputError
echo.
echo Client code "%ClientCode%" or schema name "%SchemaName%" is not valid.
set "InputAgain=Y"
set /P "InputAgain=Enter data again (Y/N)? "
if /I "%InputAgain%" == "Y" goto UserPrompt
if /I "%InputAgain%" == "YES" goto UserPrompt
endlocal
This batch file first defines defaults for client code and schema name making it possible for the user to simply hit key RETURN or ENTER when defaults are okay.
Next the window is cleared and the user is prompted for client code and schema name. The input of the user is not validated at all.
A very simple check is made if the appropriate directory (or file) exists.
The current directory is changed if a directory according to entered data exists.
If the directory does not exist, the user is asked if data input should be repeated in case of a typing mistake. The user can input Y or YES in any case to redo data input. Otherwise the batch script exits without changing the directory.
There is no real effort made on validating user input strings and verifying if the entered strings really lead to a directory and not a file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?