Changing multiple files batch file doesnt work - batch-file

This is a very simple batch file I did to start practicing with the command line, but for some reason it wont work properly. Here the code:
::Change names
#echo off
set /p DirLoc = "Enter file location:"
cd %DirLoc%
echo %DirLoc%
dir
set /p SetFrom = "What file type is it?"
set /P SetTo = "What file type do you want?"
echo Change from %SetFrom%
echo to %SetTo%
rename *.%SetFrom% *.%SetTo%
echo process has been completed
pause
echo on
For some reason, when I insert the folder location, which in my case is "C:\Users\Marco DS\Desktop\Test", the program will only go till "C:\Users\Marco DS\Desktop", which is no good. I have tried a few alternatives of my entries, but I never manage to get the desired directory.
Thanks for any suggestions.

Part of your problem is that, in Batch, you should not use spaces or quotation marks when setting variables, or else they will be part of the variable. Unlike many languages, Batch reads all whitespace characters as part of the code. In this case, the name of the variable is set as %DirLoc % instead of just %DirLoc%. In order to make your code work in the way you want, you need to remove all the unwanted spaces and quotation marks in your code.
For example:
set /p DirLoc = "Enter file location:" becomes set /p DirLoc=Enter file location:
To see proof of this, try writing echo %DirLoc % right after echo %DirLoc% and running the code.

Related

Batch File - How to copy text from file, and then update it to a new value

Each time I open the batch file, I would like it to read the information currently stored in the text file, and then apply that stored information it pulled to calculating a new integer.
I'm trying to figure out how to get a number copied from a text file, stored as a variable, and then updated to a new integer in that text file, say adding 1 to the value.
I've been sifting through information online, and everything seems to point in a different direction.
Here is a test code I've gotten from digging thus-far:
set file="Test.txt"
set /a _Counter =< %file%
echo:%_Counter%
set /a "_Update=%_Counter%+1"
echo:%_Update% >%file%
timeout /t 10
For some reason when I try to get the information for the counter, it doesn't pull any data from the text file, and I'm left with this line output by the batch file.
F:\Users\Test\Documents\JumbledDirectory> set /a _Counter = Directory\Test.txt 0<F:\Users\Test\Documents\Jumbled
The most common answer I've seen is to use something along the lines of
set /p _Counter=< Test.txt
echo %_Counter%
As seen here: Windows batch command(s) to read first line from text file
But upon doing this I've either ended up with
echo:%_Counter%
being completely blank, or it defaults to 0 each time.
Any help would be appreciated as I've sadly been trying to find how to get this simple function for around 6 hours now.
#ECHO Off
SETLOCAL
set "file=q72474185.txt"
set /p _Counter=< "%file%"
echo:%_Counter%
set /a _Update=_Counter+1
echo:%_Update% >"%file%"
TYPE "%file%"
GOTO :EOF
When you use the point-click-and-giggle method of executing a batch, the batch window will close if a syntax-error is found or the script runs to completion. You can put a pause after statements and home in on the error, but better to open a 'command prompt' and run your batch from there so that the window remains open and any (error) messages will be displayed.
The error message would be about missing operand.
I've changed the filename as I track each question I respond to with its own set of data.
Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier.
set /a does not expect input from anywhere, it simply performs the calculation and assigns the result. Quotes are not necessary so I've removed them. % are also not required in a set /a but can be required if you are using delayedexpansion.
set /p expects input, so I've used that to read the file. Note that set /a disregards spaces, but set and set /p will include the space before the = in the variablename assigned, and _Counter & _Counter are different variables.
So having the batch in the same directory as the textfile this will work:
REM get input of file as Counter
set /p Counter=<number.txt
REM add a number to Counter and assign it as Counter
set /a "Counter=%Counter%+3
REM empty the file
break>number.txt
REM write Counter in the file
echo %Counter% >> number.txt

What does =< mean in a batch file after SET /P and variable name?

So my friend gave me a batch file he wanted me to check if everything is correct, but I've got no clue what =< does in this.
:artthou_54
mode 50,20
cls
set videopath=0
title Art thou sure?
set /p videopath=<\DataTron\Ainstro\YePathToVido.dat
if %videopath%=="" echo Video Path = %videopath%
if %videopath%=="C:\Vodie" echo It seems you have the same path as the creator
set /p videopath="Would you like to open %VideoPath%? (Y/N): "
mode 50,20
if %videopath%==Y goto videohole-b
if %videopath%==N goto videohole
if %videopath%==y goto videohole-b
if %videopath%==n goto videohole
if %videopath%==back goto videohole-c
if %videopath%==exit exit
goto Art-thou-unsure
That line sets the first line of YePathToVido.dat to the variable videopath.
Normally, set /p gets input from the user and reads in until it receives a CRLF.
However, < redirects input from the specified file and sends it to the set /p command. Since set /p reads until it receives a CRLF, this effectively tells the command to read from the start of the file until the end of the first line.
On a side note, those first two if statements are incorrect because batch compares everything on both sides of the ==, including the quotes. Those lines need to change to if "%videopath%"=="" and if "%videopath%"=="C:\Vodie", respectively.

Batch Remembering Configuration

I'm trying to create a batch code to remember user input. Like if you put in "echo What is your name?" then put in your name. It would then save it somewhere to remember it or recall it later on. Even if it were to create and write it to a file to remember things from.
This should do the trick:
#echo off
cls
set INPUT=
set /P INPUT=Input your name (it will be logged in names.txt): %=%
echo Your inputted name was: %INPUT%
echo %INPUT% >>names.txt
Here's a demonstration of using Windows batch commands to write user input to a file. Note the file will be written in the same directory you run the batch file from.
set /p name="What is your name: "
#echo off
echo %name% > name.txt
The /p flag turns this into a prompt, setting the value of name to the result of the user input string. #echo off prevents echoing the next line, which echoes the stored variable into a text file called name.txt. If name.txt doesn't exist, it's created; if it does exist, it's overwritten with this value.

Using xcopy or copy for a single file from multiple folders

So in the batch script I'm building I am taking a single file from a folder, copying it over to a destination folder, and renaming it based on the number of times that the script has been looped. Essentially I need to take a file that's named the samething from a bunch of different folders spread across multiple computers at times and copy them into a new folder to work with. I've read up on xcopy and copy as that seemed like the thing to use but I haven't been able to find anything that lets me tell it to only copy over a single named file. I've posted what I have so far for the script below with commented lines for the sections I haven't figured out:
ECHO off
SETLOCAL enabledelayedexpansion
ECHO Note: Your combined permission list cvs can be found in the desktop folder
SET /A #=-1
:start
SET /A #+=1
:again
ECHO Please input the file path to the permissionoutput.txt
SET /p permissionoutputpath=
SET "sourcefolder=%permissionoutputpath%"
SET "destinationfolder=C:\Users\kayla\Desktop\HOLDER-CombinedPermissionsLists"
IF not exist "%sourcefolder%\permissionoutput.txt" Echo file not found&goto again
copy "%sourcefolder%\permissionoutput.txt" "%destinationfolder%\permissionoutput%#%.txt"
ECHO Add another file to combine: y or n?
SET /p addanotherfile=
if %addanotherfile%==y goto :start
UPDATE: Code corrected with answer to be fully functional for use as a reference
SET /A #=-1
:start
SET /A #+=1
:again
ECHO Please input the file path to the permissionoutput.txt
SET /p permissionoutputpath=
SET "sourcefolder=%permissionoutputpath%"
SET "destinationfolder=C:\Users\kayla\Desktop\HOLDER-CombinedPermissionsLists"
IF not exist "%sourcefolder%\permissionoutput.txt" Echo file not found&goto again
copy "%sourcefolder%\permissionoutput.txt" "%destinationfolder%\permissionoutput%#%.txt"
ECHO Add another file to combine: y or n?
SET /p addanotherfile=
if /i "%addanotherfile%"=="y" goto start
# is a legitimate variable-name. It's initialised to -1 then incremented on each loop through :start so the first value it will have when it's used is 0. (If you want to start at 1 just initialise it to 0 instead)
Next - your sets - BUT spaces are significant in a string set command are would be included in the variablename/value assigned if present in the set instruction. "quoting the assignment" ensures any stray trailing spaces on the line are not included in the value assigned.
Well - next, make sure the file exists and if it doesn't, then produce a message and loop back to :again which bypasses the increment of #.
Otherwise, simply copy the file. You're aware of its sourcename, and your destinationname is constructed by including %#% to include the current value of # (all batch variables without exception are strings - the set /a instruction merely converts from string to binary to perform the required calculation, then converts the result back to a string for storage in the environment.)
Finally, interpreting the request to add another file. if /i makes the comparison case-insensitive. Since you have no direct control over the user's response, "quoting each side" ensures the if syntax isn't violated in case the user enters "yup sure 'nuff" or some other unexpected response.
The leading colon is not required in a goto. I prefer to omit it to keep conguity with the call command where no-colon means an external routine will be called and a colon means the routine is in this batch file.

Make A Batch File Remember Something

I'm having trouble with a batch file. I need it to remember somthing for a long
period of time. Lets say I have a variable called %Rememberme%: I need to remember this for lets say a year for some reason. How can I make my batch file remember that variable?
Well... I could echo the variable to a file using the command
echo >>%Rememberme% C:\File.txt
Well the thing is I can't have that. I need it to be remembered some other way.
Or somehow I need to give the batch file administrator rights so that it can read or write to a file. Is there a way to do this?
You can use environment variables to do this, but be careful not to overwrite existing variables.
EX:
SETX REMEMBERME "C:\windows\system32"
And then in another file,
>echo %REMEMBERME%
>C:\windows\system32
The documentation for SETX is here: TechNet - SETX:
Important remark from the link:
Setx provides the only command-line or programmatic way to directly and permanently set system environment values. System environment variables are manually configurable through Control Panel or through a registry editor. The set command, which is internal to the command interpreter (Cmd.exe), sets user environment variables for the current console window only.
Here's an example of saving a variable in a file name. This obviously assumes the variable is limited to filename-friendly characters (like a number).
:: Reading variable
for %%f in (*.myvariable) do (
set myvariable=%%f
)
:: Remove extension
set myvariable=%myvariable:~0,-11%
:: Setting variable
del *.myvariable
echo. > "%myvariable%.myvariable"
echo %myvariable%
You can also store the variable inside the text file, but this requires opening the file in order to read the variable.
:: Reading variable
for /F "tokens=*" %%A in (myvariable.txt) do (
set "myvariable=%%A"
)
:: Setting variable
echo %myvariable%> myvariable.txt
echo %myvariable%
Your question is not clear. It have not any example nor a clear description of the request, so I can only guess...
The obvious point first: how to have a variable in a Batch file that remember its value for a long period of time? (i.e.: always) Easy: just define the variable in the Batch file:
set Rememberme=The value to remember
Of course, previous method does not allows to change the value of the variable, but you had mentioned nothing about this point in your request: "the value of the variable may be changed"...
Although SETX command should work, it requires admin rights and SETX is not designed for cases like this one. For example, what happens if the Batch file is changed or is not used anymore in a given computer? Well, the last value of the variable will remain in such computer for ever!
The second obvious solution is to write the variable into a separate file and read it from there when the Batch file start. If the separate file is a data file, the method described by Matt Johnson should work and it does not require administrator rights. You must note that the separate file may also be a Batch file, so the value of the variable may be read via a simple call statement:
rem Save the value
echo set Rememberme=%Rememberme%> setTheValue.bat
rem Read the value
call setTheValue.bat
However "the thing is you can't have that, so you need to be remembered some other way", although you don't explain the reasons for this restriction...
Another solution (that I think is what you are looking for) is to set the definition of the variable in the same Batch file:
rem Read the variable at beginning of the Batch file:
call :setTheValue
echo Value = %Rememberme%
rem The rest of the Batch file goes here
. . .
rem If the value needs to be changed:
if %changeValue% equ "yes" (
rem Do it:
echo set Rememberme=%Rememberme%>> "%~F0"
)
rem End the Batch file
goto :EOF
rem Define the subroutine that set the value:
:setTheValue
set Rememberme=Initial value of the variable
In previous code "%~F0" represent the name of the running Batch file itself. This way, each change in the variable value will append a new line at the bottom of the Batch file.
first:
echo >>%Rememberme% C:\File.txt
is wrong. It tries to write the string "C:\File.txt" into a filename referenced by the variable %rememberme%. What you want is:
echo %Rememberme%>>c:\File.txt
(or only one > to overwrite the file)
Second: if you have no permission to write to the root-directory, use another directory, where you have, for example:
echo %Rememberme%>%userprofile%\file.txt
or
echo %Rememberme%>%public%\file.txt
Note: be sure, there is no space between %Rememberme% and >; it would become part of the string, if you try to read it back.
to read it back, use:
set /p "remembered=" <%public%\file.txt
Here. This should help.
#echo off
echo What would you like to do?
echo 1. Enter your name
echo 2. Load your Name
choice /c 12
if %errorlevel% equ 1 goto newname
if %errorlevel% equ 2 goto loadname
:newname
cls
echo Input your name
set /p name=Name:
echo Your Name is saved!
::Here is the command where your name saves to a file.
(
echo %name
)>yourname.name
pause
exit /b
:loadname
cls
::Here is the command where it loads your name
(
echo %name%
)<yourname.name
echo Your Name: %name%
pause
exit /b

Resources