Batch file if then statement from user input - windows

Brand new here, and brand new to scripting. So, I'm struggling with this and I know I shouldn't be.
I have a batch file that currently scans and unpacks zip files. All I'm trying to do is add an input line for Business Date at the top that can then be referenced in the unpacking to make sure the dates are correct. Here is the file as it exists (I've added the user input just don't know how to reference it):
echo off
:Ask
echo Please enter Business Date (MMDDYYY)
set INPUT=
set /P INPUT=Type input: %=%
c:
cd\502
erase *.prn
7z e "\\svr-dc\ftp site\502\daily\data1.zip"
copy sz*.* sales.xls
copy sc*.* cosales.xls
copy aj*.* money.xls
copy cc*.* count.xls
pause
Instead of a pause there I would like for the file to run through all the directories, they are 502 to 607, and tell me whether the filename listed in the . is the same as the user entered business date. Then, run through the rest of the directories doing the same thing. Once it's verified that I'd like to have a .txt file open with any business dates that didn't match. Does that make any sense? Any help would be appreciated.
Thanks so much.

...
c:
FOR /L %%X in (502,1,607) DO (
cd\%%X
erase *.prn
7z e "\\svr-dc\ftp site\%%X\daily\data1.zip"
copy sz*.* sales.xls
copy sc*.* cosales.xls
copy aj*.* money.xls
copy cc*.* count.xls
)
You would use %input% to access the value that was entered as INPUT, but you give no clue to how "to make sure the dates are correct."
Hmm - given further information (perhaps...)
...
c:
FOR /L %%X in (502,1,607) DO (
cd\%%X
erase *.prn
7z e "\\svr-dc\ftp site\%%X\daily\data1.zip"
if exist sz%input%*.prn (
copy sz*.* sales.xls
copy sc*.* cosales.xls
copy aj*.* money.xls
copy cc*.* count.xls
) else (
echo Repoll %%X First>>C:\Users\Boster\Desktop\RePoll.txt
)
)
It's critical that the ( occurs on the same physical line as the if and that ) else ( all appears on the same physical line.

You asked a couple of question so instead of writing one batch script I thought I should break it down to explain how it would answer your questions:
1- Use %INPUT% to reference your variable/user input
2- If you will always have 502 to 607, then you can loop through them using a for loop
FOR /L %%G IN (502,1,607) DO echo %%G
3- To check if there exist a file/folder with the same value as the user input use an if EXIST %INPUT% statement
There are quite a few tutorials out there, here is one that walks you through batch file scripting

Related

Read a file name from a text file then search the hard drive for it using batch script

I am just beginning to write my own batch scripts and currently I am trying to develop a small batch script to read a text file containing a list of specific file names with extensions one at a time. After reading the file name, search the hard drive for that file and if found, move it to a specific directory.
This is the code I have developed thus far. It works as long as the files you are looking for are in the same directory. The OS I am using is Windows 8.1.
#echo off
cls
echo.
echo.
echo.
for /F "delims=" %%a in (VIRUS_LIST.txt) do (
echo searching for %%a
echo.
For /R %%G in (%%a) do (
if exist %%a (
copy "%%G" "c:\vault"
echo moving file at %%G to c:\vault
echo.
)
)
)
pause
Here is how I would like it to work; 1. read the file name from the VIRUS_LIST.TXT file, 2. scan drive C for that file, 3. If found copy or move it to a directory on C drive called C:\vault.
The list file I am using is called VIRUS_LIST.TXT that holds the file names to search for, and if found they would be moved to C:\VAULT to be processed later. If anyone can offer any help it would be greatly welcomed.

Run Batch Script Across Subfolders (Recursively)

I regularly have to rename hundreds of files across a subfolder structure. I have been creating a batch file consisting of all my rename commands, and manually pasting this into each subfolder to execute one subfolder at a time. I'd like to revise the batch script so that it executes against all subfolders in one fell swoop, run from the parent directory just once.
My renaming is very manual, and so I need to create a discrete entry for each file. For example, here are three lines:
REN STWP01_00669087* BCBSRI-01849351*
REN BCBSRI-01849357* 2011-12-19_BCBSRI-01849357*
REN STWP01_00669094* BCBSRI-01849369*
I've experimented with the FOR /R command, including trying a separate batch file that calls my renaming batch file (via the CALL command). No luck.
I have to assume that this is simple, but I'm a batch novice, so any help would be appreciated.
Thanks!
#Magoo,
Thanks so much for your response. Your approach is going to be far more efficient than my own so far.
A couple of questions. Please bear with me as I am a total novice with batch commands.
Here's what I did: I saved your code to a .BAT file ("RRename.bat"), modified my filenames as per your instructions and saved those to a text file ("Filenames.txt"), and then run this command from the command line: {RRename.bat Filenames.txt}.
The resulting command windows confirm correct renaming. And so I removed the ECHO and PAUSE commands and re-ran. No luck. Just a bunch of Command windows confirming the directory.
Ideally I'd love to save this as a .BAT file and simply drop this in the top-level directory, together with the data file that contains the old names and new names of the files. And so, a double-click of "RRename.bat" will parse the content of "Filenames.txt" and work its way through all subfolders, renaming wherever matches are encountered. Boom.
To that end:
1. How do I make it so {SET "sourcedir=} indicates the current directory (i.e. the directory in which the batch file is located)? This way I wouldn't ever need to change this variable. (I should note that I am running this script on a network location, which requires me to map the drive, resulting in a different drive letter every time.)
2. How do I hard-code the name of the data file into the script itself? My goal is an easily replicated process minimizing user input (save for the content of the data file).
3. How do I stop the individual command windows from appearing? I'll be renaming thousands of files at a time and don't want to see thousands fo corresponding command windows.
Thank you!
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
:: read parameters
SET "filename1=%~1"
SET "filename2=%~2"
IF DEFINED filename2 GOTO name
IF NOT DEFINED filename1 GOTO :EOF
:: 1 parameter - must be filename
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO START /min "ren %%a" "%~f0" %%a
GOTO :eof
:: we have 2 parameters so rename pattern 1 to pattern 2
:name
FOR /r "%sourcedir%" %%a IN ("%filename1%*") DO CALL :process "%%a"
PAUSE
GOTO :EOF
:: Process the filenames and actually do the rename
:process
:: Name of file to be changed - name and extension of %1
SET "changeme=%~nx1"
:: REPLACE up-to-from-pattern with nothing = remainder of name/extension
CALL SET "endpart=%%changeme:*%filename1%=%%"
:: and RENAME...
ECHO(REN "%~1" "%filename2%%endpart%"
GOTO :eof
You would need to change the setting of sourcedir to suit your circumstances.
Revised data file
STWP01_00669087 BCBSRI-01849351
BCBSRI-01849357 2011-12-19_BCBSRI-01849357
STWP01_00669094 BCBSRI-01849369
Aimed at processing the above file, renaming files starting (column1 entries) to start (column2 entries.)
Method:
Run the batch as
batchname filename
This will execute the batch, processing filename
How:
having set the directory name to start processing from, set filename1&2 to the values of the parameters supplied.
If only 1 is supplied, it is the filename, so process it line-by-line and START a new process /min minimised "with the window name in the first set of quotes" and execute this same batch with the data from each line of the file in turn, then finish by going to :eof (end-of-file - built-in to CMD)
The sub-processes all have 2 parameters (eg BCBSRI-01849357 2011-12-19_BCBSRI-01849357) so processing passes to :name. This runs a for /r loop, from the specified source directory, with the name specified from the first column+* and executes :process passing the filenames found as parameter 1.
:process sets changeme to the filename in question, calculates endpart by removing the string filename1 from changeme which will deliver the er, end part.
Then simply rename the supplied filename to the replacement name+that endpart calculated.
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.
The PAUSE is just to allow the proposed changes to be seen. Once the process has been verified, change the PAUSE to EXIT.
AAMOI, running
*batchname* STWP01_00669094 BCBSRI-01849369
for instance, would execute the recursive-rename from STWP01_00669094* to BCBSRI-01849369*
Sadly, "No luck" is meaningless.
I have made a minor, but significant change to the instructions. The PAUSE should be changed to an EXIT after testing.
After testing, the ECHO(... line should become
REN "%~1" "%filename2%%endpart%"
which actually executes the rename. If you've just deleted the line, it would explain the no-visible-result.
Having restored the original code and verified against a small representative dummy subtree, change the echo(... line and test again. The filenames should change. If not, something is dreadfully wrong. Needless to say, this works perfectly happily for me...
Then try again with the PAUSE changed to EXIT. This time, the windows generated will appear on the taskbar and then disappear when the rename for that line of the input file has finished. This will happen once for BCBSRI-01849357 rentwo for instance - not once for each individual file rename occurring.
To hard-code the filename, remove the line
IF NOT DEFINED filename1 GOTO :EOF
and replace
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO START /min "ren %%a" "%~f0" %%a
with
FOR /f "usebackqdelims=" %%a IN ("YOURFILENAMEHERE") DO START /min "ren %%a" "%~f0" %%a
For the "run from here" command, change
SET "sourcedir=U:\sourcedir"
to
SET "sourcedir=."
. means "the current directory"
If you place thisbatchfilename.bat into any directory on your PATH then you can run the routine simply by executing thisbatchfilename.
You can display your path by typing
path
at the prompt. PATH is the sequence of directories searched by windows to find an executable if it isn't found in the current directory. To chane path, google "change path windows" - experienced batchers create a separate directory on the path for batch files. Sometimes, they name the directory "Belfry".

Batch file to sort files and list missing

I am trying to write a batch file that would read rows/lines from a txt file containing a list. The batch file would then copy the documents that match, and produce a list of missing files.
So far, the code successfully copies the files that it matches, but it also fills the "Missing.txt" file will exact contents of the input list, rather than simply the missing files.
#echo off
::Requests name of list file to be used by batch file
echo Enter list file name and press enter
set /p var=
mkdir %userprofile%\Desktop\%var%\
set /A lis=1
::Logic to search for files based on contents of list inputted by user at start.
for /f "tokens=*" %%i in (%var%.txt) DO (
call :processline %%i
IF NOT EXIST %%i (echo %%i>>%userprofile%\Desktop\%var%\Missing.txt)
)
pause
::Function called processline
::Assigns a string/value to variable "line"
::Copies a file with name = "line" to the user's desktop
::Renames the file to include a number reference, based on original list being searched
::Increments number for next file to be searched,copies and renamed
:processline
echo line=%*
xcopy /s %*.* %userprofile%\Desktop\%var%
move /Y %userprofile%\Desktop\%var%\%*.pdf %userprofile%\Desktop\%var%\%lis%_%*.pdf
set /A lis=%lis%+1
:eof
I suspect my problem is within the "for" logic, although there might be a way to input missing file names within the processline function.
Any help or advice would be much appreciated.
It's command order: :processline subroutine moves something, maybe including %%i file. I'd use next code snippet:
IF EXIST "%%~i" (
call :processline %%i
) ELSE (
>>"%userprofile%\Desktop\%var%\Missing.txt" echo %%i
)

How to append string after file extension via batch file

Checking the integrity of zip archives recursively how can i rename bad files in a folder by appending a string after the file extension via a batch file under Windows?
I tried this script and it gives me no errors but doesn't rename bad files either.
FOR /R \backup %%A IN (*.zip) DO (
7z t "%%A" | FIND "Everything is Ok" || ((REN "%%A" "%%A.bad") & (ECHO.%%A BAD >> error.log))
)
I have experience in PHP scripting and understand this code block in general (the meaning of the pipe and the logical OR operator). However, i have absolutely no experience in Batch-scripting and adopted the script from this source. From what i understand the check receives either an "OK" or adds an entry to the log file and renames the file. The log entry is added, however the renaming is not applied. I don't understand why. Can you tell me what is going wrong and how it would have to look to work as intended?
You can use this batch code for your task.
#echo off
rem Test all ZIP files recursive from directory backup in root of
rem current drive and append .bad to those ZIP files not validate.
rem The names of those files are additionally written into an
rem error.log text file in current working directory.
for /R "\backup" %%A in (*.zip) do (
7z.exe t "%%A">nul
if errorlevel 1 (
ren "%%A" "%%~nxA.bad"
echo %%A BAD>>error.log
)
)
In help of 7-zip there is a page about Exit Codes. As it can be read on this help page any value greater 0 means something was wrong.
Therefore if errorlevel 1 can be used to check if the test on the ZIP file was positive (exit code is 0) or failed (value is greater or equal 1).
Look on help output in a command prompt window after entering if /? or help if for details about errorlevel. if errorlevel 1 means: if exit code of previous command was greater or equal 1 then ...
Further command ren requires just new file name without path as second parameter as otherwise it does not rename the file specified with or without path as first parameter. This is the reason why %%~nxA must be used as second parameter for command ren to reference just name and extension of the file to rename. Help of command for output after entering for /? or help for contains a list of those modifier letters for a file name.

Bulk renaming files in relation to the folder names

I am very new to coding and bulk processes but i am looking for a command line SPECIFICALLY for windows command prompt and i am wondering if such a thing exists. So I have a folder containing 111 subfolders, with each subfolder containing between 20 and 40 png image files. Each subfolder is named 001-111 accordingly and the png files are ordered how i want them, however i am looking for a command line that would be able to quickly and efficiently name all the pngs in the folders to the name of the folder followed by the png number in brackets
e.g. for folder 037, i would want the png's to be renamed to: 037(1), 037(2), 037(3) etc...
I am hoping for the best although i am unsure such a code may not be possible or be simply done.
Also if you come up with a code that achieves this process, it would be great if you could reply with the simple command line that i could use rather than a full explanation because i am new to coding and far from fluent with the language or terms or how things work. I know this same process can be achieved by going select all>rename (ctrl a>f2) and renaming to the folder name however i need to use this process frequently and dont want to have to open each folder, i would rather have a command line for cmd that would do it swiftly
Thank you and a simple answer would be greatly appreciated
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "parentdir=u:\parent"
FOR /l %%a IN (1001,1,1111) DO (
SET dir=%%a&SET "dir=!dir:~1!"
FOR /f "delims=" %%i IN ('dir /a-d /b "%parentdir%\!dir!\*.png" 2^>nul') DO (
ECHO REN "%parentdir%\!dir!\%%~nxi" "!dir!(%%~ni)%%~xi"
)
)
GOTO :EOF
Test results:
Starting directory :
u:\parent\001\1.png
u:\parent\037\1.png
u:\parent\037\2.png
u:\parent\111\999 with spaces in name.png
Script response
REN "u:\parent\001\1.png" "001(1).png"
REN "u:\parent\037\1.png" "037(1).png"
REN "u:\parent\037\2.png" "037(2).png"
REN "u:\parent\111\999 with spaces in name.png" "111(999 with spaces in name).png"
Obviously, you'd need to replace the value assigned to parentdir with your actual target directory name.
The script will report the renames it proposes to do. To actually invoke the rename remove the ECHO keyword.
I would create a batch file like so:
renamepng.bat:
cd %%1
if ERRORLEVEL 1 goto end
for %f in *.png do mv "%f" "%%1(%f).png"
cd ..
:end
This will attempt to cd to the directory name provided on the command line, abort if that fails, then rename all the .png files and return to the previous directory
then call it like so:
for %d in ??? do call renamepng.bat %d
which will loop through all 3-character file and directory names in the current directory, can call the batch file on each one. Using call instead of just the batch file name causes execution to return to the loop when the batch finishes.

Resources