Batch parameters with spaces for loop recursive move - windows

I am trying to put a batch together to move all zip files back one directory from the current directory in a recursive move where I specify the search directory from the parent.
In example, the current directory is download and the sub to recursive search is a command line parameter.
I then want to move the *.zip back one directory from download. I don't want to search in any other directory other than the one I specify.
>movezipdir junk 2009
This outputs junk 2009. Then junk was unexpected at this time.
Here's what I have but the for loop doesn't like the variable with spaces...
#echo off
IF %1.==. GOTO No1
set DirName=%*
echo %DirName%
For /d %DirName% in ( *.* ) do (
For /d %%e in (""%DirName%"\*") do (
rem move /Y "%%e\*.zip" "%CD%\.."
echo %DirName%
rem rd /S /Q "%%e"
)
rem rd /S /Q %DirName%
)
GOTO End1
:No1
ECHO No Directory Specified
GOTO End1
:End1
It would be great if someone could point me in the right direction. Thanks. Ken

#echo off
rem :: check if the args is not nul
if [%1] == [] (
goto error
) else (
for /f "usebackq tokens=1*" %%i in ('echo %*') do (
set "dirname=%%~i"
)
)
rem check if the specified args correspond to a directory
if exist "%dirname%\nul" echo %dirname% it's a directory || goto error
set /a c=1
setlocal EnableDelayedExpansion
for /f "tokens=* delims=" %%a in ('dir /b /s /a-d "%dirname%\*.txt"') do (
rem usage: move [{/y | /-y}] [Source] [Target]
rem https://technet.microsoft.com/en-us/library/cc772528.aspx
rem http://ss64.com/nt/move.html
rem %cd% here are redundant because when target are omitted,
rem the target are always the current directory
echo move /-y "%%a" "%cd%"
rem break loop after 5 iterations.
rem You can remove it if the test are Okay
if [!c!] equ [5] goto break_loop
set /a c+=1
)
:break_loop
rem usage: RD [/S] [/Q] [drive:]path
echo rd /s /q %dirname%
exit /b 0
:error
echo Error: No directory specified or invalid arguments
echo Usage: %~0 ^<full path of the directorys^>
echo Example: %~0 c:\user\janne\MyDocuments
exit /b 0

Related

Use a Batch File to list files and allow the user to select which file to copy into a new destination

I am a newbie to Windows Scripting.
I am trying to list some txt files in several sub directories & want to copy a user selected file to a new destination. Please note that the file name is unique in different locations.
I got the first part to work (Listing out the files & locations) using the following script, but I am unable to copy the selected file to the new location.
#ECHO OFF
SET index=1
SETLOCAL ENABLEDELAYEDEXPANSION
SET FFPath="C:\Scripts - Backup Server\DKXpress_bkp"
SET NewPath=C:\DKServer
ECHO Recursively searching %FFPath%
echo.
FOR /F "delims=" %%f in ('DIR %FFPath%\*.txt /a:-d /s /b') DO (
SET file!index!=%%f
ECHO !index! - %%f
SET /A index=!index!+1
)
SETLOCAL DISABLEDELAYEDEXPANSION
SET /P selection="select file by number:"
SET file%selection% >nul 2>&1
IF ERRORLEVEL 1 (
ECHO invalid number selected
EXIT /B 1
)
SET NewFile=file%selection%
ECHO Copying %NewFile% to %NewPath%
ECHO.
COPY /Y "%NewFile%" "%NewPath%"
ECHO.
PAUSE
I think I am doing this part wrong
SET NewFile=file%selection%
Thank you all in advance
You don't need to set an index variable or delayed expansion, if you let Find do the work for you:
#Echo Off
Set "FFPath=C:\Scripts - Backup Server\DKXpress_bkp"
Set "NewPath=C:\DKServer"
Echo Recursively searching %FFPath%
Echo=
For /F "Delims==" %%A In ('"Set File[ 2>Nul"') Do Set "%%A="
For /F "Tokens=1* Delims=]" %%A In (
'"Dir /B/S/A-D-S-L "%FFPath%\*.txt" 2>Nul|Find /N /V """') Do (
Echo %%A] %%B
Set "File%%A]=%%B"
)
Echo=
Set /P "#=Select file by number: "
Echo=
For /F "Tokens=1* Delims==" %%A In ('"Set File[%#%] 2>Nul"') Do (
Echo Copying %%B to %NewPath%&Echo=
Copy /Y "%%B" "%NewPath%"
GoTo :End
)
Echo Invalid number selected
:End
Echo=
Pause
You need to use delayed expansion to get the file name assigned to the variable correctly.
SET NewFile=!file%selection%!
Remove the setlocal to disable delayed expansion.
You can try something like that :
#ECHO OFF
:Main
cls
SET index=1
SETLOCAL ENABLEDELAYEDEXPANSION
SET FFPath="C:\Scripts - Backup Server\DKXpress_bkp"
SET "NewPath=C:\DKServer"
ECHO Recursively searching %FFPath%
echo.
FOR /F "delims=" %%f in ('DIR %FFPath%\*.txt /a:-d /s /b') DO (
SET filepath[!index!]=%%f
ECHO [!index!] - %%~nxf - %%f
SET /A index=!index!+1
)
echo(
echo select file by number :
set /p Input=""
For /L %%i in (1,1,%index%) Do (
If "%INPUT%" EQU "%%i" (
ECHO Copying "!filepath[%%i]!" to "!NewPath!"
COPY /Y "!filepath[%%i]!" "!NewPath!"
)
)
echo Copying another file ? (Y = Yes or N = No) ?
set /p input2=""
If /I "!input2!"=="Y" (
goto :Main
) else (
goto :eof
)

Counting files and directories at each directory level from a batch file

I have successfully used a batch file which counts the total number of files and directories in a root directory.
Directory structure:
Here is the current script: (gets the number of files and folders returning subfolders up to the nth child).
#echo off
set "drive=D:\Download\app"
for /d %%r in ("%drive%\*") do (
echo Path: %%~fr
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s %%~fr ^| find /i "bytes"') do if "%%j"=="File(s)" (
set numfiles=%%i
)ELSE (
for /f %%a in ('dir /b /s /ad %%~fr ^|find /c /v "" ') do set numfolders=%%a)
echo Files: %numfiles%
echo Folds: %numfolders%
)
First the program outputs the total number of files and total number of folders in the root directory and then it goes to first subfolder and outputs the same for it's whole tree, then it moves to the next folder at that level etc.
EDIT
I have done the part where it go to 1 level of subfolders and get the total number of files and folders but I want it up to N number of subfolders which mean it should output total number for each and every folder in root directory.
Here is the extended code.
#echo off
setLocal EnableDelayedExpansion
set "drive=C:\Users\%USERNAME%\Downloads\Sandukchi"
set numfiles=
set numfolders=
set count=0;
for /d %%r in ("%drive%\*") do (
echo %%r
SET /A count=count + 1
for /d %%a in ("%%r\*") do set modifiedDate=%%~ta
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s "%%r\*" ^| find /i "File(s)"') do set fileSizeBytes=%%k
for %%* in ("%%r") do set folderName=%%~nx*
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s "%%r\*" ^| find /i "bytes"') do if "%%j"=="File(s)" (
set numfiles=%%i
)ELSE (
for /f %%a in ('dir /b /s /ad "%%r\*" ^|find /c /v "" ') do set numfolders=%%a)
echo Last Modified Date: !modifiedDate!
echo Folder Size: !fileSizeBytes! KB
echo Total Number of Files: !numfiles!
echo Total Number of Folders: !numfolders!
(
echo !count! %%r !folderName! !modifiedDate! Total Size !fileSizeBytes!KB Total Files !numfiles! Total Folder !numfolders!
echo.
)>>output.txt
)
#ECHO Off
SETLOCAL
SET "sourcedir=."
SET "tempfile=%temp%\##__##.txt"
SET "dirname="
(
FOR /f "tokens=1,2,*delims= " %%w IN (
'dir /s "%sourcedir%\*" '
) DO (
IF "%%w"=="Directory" (
SET "dirname=%sp256%%%y"&SET /a fcnt=0&SET /a dcnt=-2
) ELSE (
FOR /f "delims= " %%p IN ("%%y") DO (
IF "%%p"=="<DIR>" SET /a dcnt+=1
)
)
IF "%%x"=="File(s)" CALL ECHO %%dirname%%*%%w*%%dcnt%%
)
)>"%tempfile%"
FOR /f "tokens=1,2,*delims=*" %%a IN ('sort "%tempfile%"') DO ECHO directory %%a&ECHO files %%b&echo subdirs %%c
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
Generates a tempfile. No attempt made to delete the tempfile as it may contain useful data.
Run a standard dir/s command, and pick out the lines which start directory (which indicates a new directoryname) and those where the third space-delimited token is <DIR> for counting subdirectories. When the lines with second token File(s) appears, output the name, filecount and directorycount to a tempfile.
Sort the tempfile and report.
Note: %%y contains the third token onwards from each line. This is retokenised, selecting the first token only (default) to %%p isolating the third token of the original line.
The tempfile is produced using * as a separator since * is not a valid filename character.
dcnt is set to -2 to start the count-of-directories because both . and .. are reported as directorynames in a dir /s.
Give a try for this code :
#echo off
Setlocal EnableDelayedExpansion
#For /D %%D in (*) DO (
Set "Folder=%%~D"
PUSHD "!Folder!"
FOR /F %%H in ('dir /a-d /b 2^>NUL^|find /C /V "" ') DO ( Set "numFiles=%%H" )
FOR /F %%I in ('dir /ad /b 2^>NUL^|find /C /V "" ') DO ( Set "numSubFolders=%%I" )
POPD
echo The Folder "!Folder!" has !numSubFolders! SubFolders and !numFiles! Files
)
)
pause & exit

Fill backup drive with newest files

I have about 12TB (and growing) library, distributed over 3 HDDs, of video files and I would like to back them up to an external harddrive. I am using Windows 10 Pro.
My backup drive has only 8TB and I would like to always backup the newest 8TB of video files. So far I have tried about 10 sync tools but none of them allowed me to copy files according to creation date.
Also with robocopy I haven't found a way to copy only the latest 8TB of files.
Any suggestions?
I have 2 batch scripts for you that do what you have asked for. The main difference between them is, that the 1st script is using where to locate all the files which will use the timestamp of the last change. To use another timestamp e.g. last access or time of creation you have to use the 2nd script I attached which uses dir.
1.
Batch script using where to locate files:
It takes minimum 2 arguments:
Usage: batch.bat <dst> <src_1> [<src_...> <src_n>]
It uses the where /r <src_n> * /t command which will build a list of all files in all subdirectories with a timestamp of the last change in the following format:
<size> <date> <time> <file name>
5397 11.07.2017 14:32:09 C:\Users\...\foo.txt
10860 12.07.2017 11:25:15 C:\Users\...\bar.log
The timestamp is of last change if you need the time of the creation or last access take the 2nd batch script below which is using dir as there is the possibility to choose between different timestamps.
This output will be written (without the column size) into a temporary file under the temp dir %TEMP% (will be deleted automatically after script) for every source that is passed via the argument list. The complete temporary file is sorted by the date and time, newest first.
This sorted output will be used to copy it into the destination folder.
Example:
Current directory in cmd is C:\...\Desktop):
batch.bat "backup_folder" "F:\folder" "F:\folder with space"
Current directory somewhere:
batch.bat "C:\...\Desktop\backup_folder" "F:\folder" "F:\folder with space"
The C:\...\Desktop\backup_folder will contain 2 folders folder and folder with space which contain all files of these source folders after the scripts operation.
In your case the batch script would copy only 8 TB of the newest files because then the drive will be full and the batch script will exit because it recognizes copy errors.
The batch script:
#echo off
setlocal enabledelayedexpansion
rem Check if at least 2 arguments are passed
set INVARGS=0
if [%1] == [] set INVARGS=1
if [%2] == [] set INVARGS=1
if %INVARGS% == 1 (
echo Usage: %0 ^<dst^> ^<src_1^> ^<src_...^> ^<src_n^>
goto :EOF
)
rem Store Carriage return character in CR (used for spinner function, see below)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
rem Set temp file name
set "uniqueFile=%TEMP%\%0_%RANDOM%.tmp"
rem Set destination path and shift to next argument
set "dstpath=%~1"
shift
rem Store src_1 to src_n arguments into src array
set idx=0
:again
rem If %1 is blank, we are finished
if not [%1] == [] (
if not exist "%~1" (
echo The following source folder doesn't exist:
echo "%~1"!
echo The program will terminate!
goto :end
)
pushd "%~1"
set "src[%idx%]=!cd!"
if [!src[%idx%]:~-1!] == [\] (
set src[%idx%]=!src[%idx%]:~0,-1!
)
set /a idx=%idx%+1
popd
rem Shift the arguments and examine %1 again
shift
goto :again
)
rem Build command string:
rem where /r "src_1" * /t ^& where /r "src_..." * /t ^& where /r "src_n" * /t ^& break"
set "command="
for /F "tokens=2 delims==" %%s in ('set src[') do (
set "command=!command!where /r "%%s" * /t ^& "
)
set "command=!command!break"
echo "Command: ^<!command!^>"
rem Clear temp file and write files to copy in it
break>"%uniqueFile%"
for /f "tokens=2,3,4,* delims= " %%F in ('!command!') do (
call :spinner
echo %%F %%G %%H %%I>>"%uniqueFile%"
)
rem Open the built file list
echo File list will be opened...
%uniqueFile%
rem Ask user if copying should start
echo Should this files copied into %dstpath%? (Y/N)
set INPUT=
set /P INPUT=Answer?:%=%
if not [%INPUT%] == [y] (
if not [%INPUT%] == [Y] (
goto :end
)
)
set "dstpathPart="
rem Sort files newest first (last changed timestamp)
for /f "tokens=3,* delims= " %%F in ('type "%uniqueFile%" ^| sort /r') do (
rem Build destination part from source folder names
call :buildDestinationPath dstpathPart "%%F %%G"
rem Prepend the destination folder
set "dstFile=!dstpath!\!dstpathPart!"
rem Make directories that doesn't exists
for %%F in ("!dstFile!") do set "directory=%%~dpF"
if not exist "!directory!" ( mkdir "!directory!" )
rem Copy files and echo it
echo copy /y "!file!" "!dstFile!"
copy /y "!file!" "!dstFile!"
echo.
rem If copying failed exit program
if errorlevel 1 (
echo Copying failed... Maybe there is no more space on the disk!
echo The program will terminate!
goto :end
)
)
goto :end
rem Function definitions
:buildDestinationPath
for /F "tokens=2 delims==" %%s in ('set src[') do (
rem Go into folder e.g.: C:\src_1\ --> C:\
pushd "%%s"
cd ..
rem file contains full path of the where command
set "file=%~2"
rem Remove trailing space
if "!file:~-1!" == " " (
call set "file=%%file:~0,-1%%"
)
rem remove src folder from file to make it relative
rem e.g. C:\src_1\foo\bar\file1.txt --> src_1\foo\bar\file1.txt
call set "dstpathPart_temp=%%file:!cd!=%%"
rem Switch back to origin folder
popd
rem If the folder name changed the substring taken was right so take next
if not [!dstpathPart_temp!] == [!file!] (
set "%~1=!dstpathPart_temp!"
goto :next
)
)
:next
goto :EOF
:spinner
set /a "spinner=(spinner + 1) %% 4"
set "spinChars=\|/-"
<nul set /p ".=Building file list... !spinChars:~%spinner%,1!!CR!"
goto :EOF
:end
del "%uniqueFile%"
goto :EOF
2.
Batch script using dir to locate files:
It takes one more argument so that you need minimum 3 arguments:
Usage: batch.bat <timeordering> <dst> <src_1> [<src_...> <src_n>]
It will generate the same list as explained above but with the help of the dir command. The dir command takes the following parameter which is the <timeordering> parameter of the script:
/tc Creation
/ta Last access
/tw Last written
The batch script:
#echo off
setlocal enabledelayedexpansion
rem Check if at least 2 arguments are passed
set INVARGS=0
if [%1] == [] set INVARGS=1
if [%2] == [] set INVARGS=1
if [%3] == [] set INVARGS=1
if %INVARGS% == 1 (
echo Usage: %0 ^<timeordering^> ^<dst^> ^<src_1^> ^<src_...^> ^<src_n^>
goto :EOF
)
rem Store Carriage return character in CR (used for spinner function, see below)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
rem Set temp file name
set "uniqueFile=%TEMP%\%0_%RANDOM%.tmp"
rem Set timeordering and destination path and shift to next argument
set "timeordering=%~1"
shift
set "dstpath=%~1"
shift
rem Store src_1 to src_n arguments into src array
set idx=0
:again
rem If %1 is blank, we are finished
if not [%1] == [] (
if not exist "%~1" (
echo The following source folder doesn't exist:
echo "%~1"!
echo The program will terminate!
goto :end
)
pushd "%~1"
set "src[%idx%]=!cd!"
if [!src[%idx%]:~-1!] == [\] (
set src[%idx%]=!src[%idx%]:~0,-1!
)
set /a idx=%idx%+1
popd
rem Shift the arguments and examine %1 again
shift
goto :again
)
rem Clear temp file and write files to copy in it
break>"%uniqueFile%"
rem call commands with all sources:
rem call :getFileInformation /TC "src_1\*"
rem /TW
rem /TA
for /F "tokens=2 delims==" %%s in ('set src[') do (
call :getFileInformation %timeordering% "%%s\*" "%uniqueFile%""
)
rem Open the built file list
echo Unsorted file list will be opened...
%uniqueFile%
rem Ask user if copying should start
echo Should this files copied into %dstpath%? (Y/N)
set INPUT=
set /P INPUT=Answer?:%=%
if not [%INPUT%] == [y] (
if not [%INPUT%] == [Y] (
goto :end
)
)
set "dstpathPart="
rem Sort files newest first (last changed timestamp)
for /f "tokens=3,* delims= " %%F in ('type "%uniqueFile%" ^| sort /r') do (
rem Build destination part from source folder names
call :buildDestinationPath dstpathPart "%%F %%G"
rem Prepend the destination folder
set "dstFile=!dstpath!\!dstpathPart!"
rem Make directories that doesn't exists
for %%F in ("!dstFile!") do set "directory=%%~dpF"
if not exist "!directory!" ( mkdir "!directory!" )
rem Copy files and echo it
echo copy /y "!file!" "!dstFile!"
copy /y "!file!" "!dstFile!"
echo.
rem If copying failed exit program
if errorlevel 1 (
echo Copying failed... Maybe there is no more space on the disk!
echo The program will terminate!
goto :end
)
)
goto :end
rem Function definitions
:buildDestinationPath
for /F "tokens=2 delims==" %%s in ('set src[') do (
rem Go into folder e.g.: C:\src_1\ --> C:\
pushd "%%s"
cd ..
rem file contains full path of the where command
set "file=%~2"
rem Remove trailing space
if "!file:~-1!" == " " (
call set "file=%%file:~0,-1%%"
)
rem remove src folder from file to make it relative
rem e.g. C:\src_1\foo\bar\file1.txt --> src_1\foo\bar\file1.txt
call set "dstpathPart_temp=%%file:!cd!=%%"
rem Switch back to origin folder
popd
rem If the folder name changed the substring taken was right so take next
if not [!dstpathPart_temp!] == [!file!] (
set "%~1=!dstpathPart_temp!"
goto :next
)
)
:next
goto :EOF
:getFileInformation
for /f "delims=" %%a in ('dir /s /b /a-d %~1 "%~2"') do (
for /f "tokens=1,2 delims= " %%b in ('dir %~1 "%%a" ^| findstr /l /c:"%%~nxa"') do (
echo %%b %%c %%a>>"%~3"
call :spinner
)
)
goto :EOF
:spinner
set /a "spinner=(spinner + 1) %% 4"
set "spinChars=\|/-"
<nul set /p ".=Building file list... !spinChars:~%spinner%,1!!CR!"
goto :EOF
:end
del "%uniqueFile%"
goto :EOF

find multiple files paths with single string

I tried to write a batch script that find all the paths of files that have the same name as the input string. right now it can find only the first file found, and i cant think of a way to make it list multiple files locations. I am not very experienced and I need some help.
this is part of the script code:
:start
cls
echo Enter file name with extension:
set /p filename=
echo Searching...
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%"') do (
set file=%%~nxb
set datapath=%%~dpb\
::the path of the file without the filename included "C:\folder\folder\"
set fullpath=%%b
::the path of the file with the filename included "C:\folder\folder\file"
goto break
)
)
:notfound
cls
echo Enter file name with extension:
echo %filename%
echo File Not Found!
ping localhost -n 4 >nul
goto start
:break
if "%datapath:~-1%"=="\" set datapath=%datapath:~,-1%
cls
echo 3 %filename% found
echo %fullpath1%
echo %fullpath2%
echo %fullpath3%
--- || ---
I want the script to search the computer and list every encountered files with the same name and I want to be able to put those files' paths into different variables.
For example, if readme.txt is the input, then I want the list of all the paths of all the files with that specific name (readme.txt) and I want to set variable for each path so I can use it after that.
input:
readme.txt
output:
3 files found
C:\folder\folder\readme.txt
C:\folder\folder\folder\readme.txt
D:\folder\readme.txt
#echo off
set filename=readme.txt
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%"') do (
echo you can do something here with %%~nxb in %%~dpb
echo full name: %%b
)
)
I see no need to set the filenames to variables, as you can process them inside your loop. But if you really need them (for some reason) in variables:
#echo off
setlocal enabledelayedexpansion
set filename=readme.txt
set count=0
for %%a in (C D E F G H U W) do (
for /f "tokens=*" %%b in ('dir /s /b "%%a:\%filename%" 2^>nul') do (
set /a count+=1
set _file[!count!]=%%b
)
)
set _file
You can try with this code :
#echo off
Title Searching for the path with the same file name
Mode con cols=80 lines=3 & Color 9E
SET /a Count=0
set /a cnt=1
set "FileName=Readme.txt"
set "Report=%~dp0Report.txt"
set "Folder2Copy=%~dp0Readme_Folder"
set "Result2Copy=%~dp0Result2Copy.txt
If exist %Folder2Copy% RD /S /Q %Folder2Copy%
If Exist %Report% Del %Report%
If Exist %Result2Copy% Del %Result2Copy%
echo(
Echo Searching for the path with the same file name
Rem Looking for fixed drives and store them into variables
SETLOCAL enabledelayedexpansion
For /f "skip=1" %%a IN ('wmic LOGICALDISK where driveType^=3 get deviceID') DO (
for /f "delims=" %%b in ("%%a") do (
SET /a "Count+=1"
set "Drive[!Count!]=%%b"
)
)
:Display
for /L %%i in (1,1,%Count%) do (
cls
Title Please wait a while ... Searching for "%FileName%" on "!Drive[%%i]!\"
echo(
echo Please wait a while ... Searching for "%FileName%" on "!Drive[%%i]!\"
Call :FindPathFile !Drive[%%i]!\ %FileName% >> %Report%
)
Start "" %Report%
Goto :AskQuestion
::***************************************************************************************
:FindPathFile <Location> <FileName>
Where.exe /r %1 %2
Goto :eof
::***************************************************************************************
:AskQuestion
cls & Mode con cols=100 lines=5
echo(
echo Did you want to make copy of all files found as name "%FileName%"
echo saved on "%Report%" ? (Y/N) ?
set /p "Input="
If /I "%INPUT%"=="Y" (
for /f "delims=" %%i in ('Type "%Report%"') do (
Call :MakeCopy "%%~i" "%Folder2Copy%\"
)
)
Call :Explorer "%Folder2Copy%\" & exit
If /I "%INPUT%"=="N" (
Exit
)
Goto :eof
::***************************************************************************************
:MakeCopy <Source> <Target>
If Not Exist "%~2\" MD "%~2\" (
if not exist "%2\%~n1" (
echo copying "%~1" to "%~2"
copy /N /B "%~1" "%~2" >>%Result2Copy% 2>&1
) else (
call :loop "%~1" "%~2"
)
)
::***************************************************************************************
:loop
set "fname=%2\%~n1(%cnt%)%~x1"
if exist "%fname%" set /a cnt+=1 && goto :loop
copy "%~1" "%fname%"
exit /b
::***************************************************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::***************************************************************************************

windows batch, setting a variable inside a nested loop

I have the below batch that reads data from a text file, the problem is in the inner loop; it should get the lat created file in the destination folder, and it just gets nothing!
here's my code:
:: Delete Files from folder
#echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak"
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups
setlocal
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
pushd "%%G"
for /F "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
set lfile=%%a
)
echo copying "%%G\%lfile%" to "%destdir%" ,,,%%H
copy /y "%%G\%lfile%" "%destdir%
E:
cd "%destdir%
E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "%destdir%/%lfile%"
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar"
echo Deleting RAR file...
SET v_test=%lfile%
SET v_result=%v_test:rar=bak%
ren "%v_result%" "%%I"
echo Ready ...
popd
)
pause
appreciate you help.
thanks.
If you'are using a set inside for body you'll need enabledelayedexpansion:
http://www.robvanderwoude.com/variableexpansion.php
edit:
:: Delete Files from folder
#echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak"
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups
setlocal enabledelayedexpansion
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
pushd "%%G"
for /F "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
set lfile=%%a
)
echo copying "%%G\!lfile!" to "!destdir!" ,,,%%H
copy /y "%%G\!lfile!" "!destdir!"
E:
cd "!destdir!"
E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "!destdir!/!lfile!"
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar"
echo Deleting RAR file...
SET v_test=!lfile!
SET v_result=!v_test:rar=bak!
ren "!v_result!" "%%I"
echo Ready ...
popd
)
endlocal
pause
#npocmaka
Thank you! You solved my problem I was working on for hours!
I had a similar problem.
I was using a nested for loop and tried to split the for loop into another batch file, but didn't work. So I used 'npocmaka's advice:
This is the batch being called which is inside another for loop.
#ECHO OFF
SET dir=%~1
SET suf=%~2
ECHO IN dir:%dir%
ECHO IN suf:%suf%
PAUSE
SET /A count=1
SETLOCAL EnableDelayedExpansion
pushd %dir%
FOR /R . %%A IN (*.%suf%) DO (
ECHO File: %%~nxA count:!count!
PAUSE
REN %%~nxA !count!.txt
CALL :increment RESULT count
)
popd
ENDLOCAL
:increment
SET /A count+=1

Resources