Batch File Skipping over FOR LOOP - loops

UPDATE
I removed the tokens=4 and it started outputting data. It is not skipping past the FOR LOOP. I was skipping too far ahead with the tokens. I am still a little confused as to why it works as a single batch and not from this batch but now at least I know what the issue was. Thank you to everyone that was looking into this for me.
I am writing a script to copy over data from one computer to another. The issue is that it is skipping over the FOR LOOP that I am calling from another FOR LOOP. If you are testing the script it requires two PC's and a mapped T: drive to somewhere on the second computer. I can write the script so it looks for an external drive if that is more helpful to someone.
FOR /F "tokens=4 skip=1" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
If I write the FOR LOOP above in a batch by itself and just echo out %%a then it works without a problem. In this, I can see that it is indeed calling :_backup but it skips directly over the FOR Loop and I am not sure why. I have written scripts like this many times but never had any that just completely ignore the FOR Loop. Can anyone take a look and assist? Thank you.
#echo off
:: Set Variables
SET _driveID=T:
SET _params=/Z /E /COPY:DT /R:1 /W:0 /XD LocalService NetworkService temp "temporary internet files" winsxs Content.IE5 cache /XF ntuser.* *.tmp /XJ /FP /NC /NS /NP /NJH
SET _regshell=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
SET _regdesktop=Desktop
:: Set Current Directory
pushd %SystemDrive%\
:: Start Menu - Create Choices and Options. Send to various places to perform the actions.
:_start
cls
ECHO Please type either option 2 or 3 and then press ENTER on the keyboard?
Echo 2. TRANSFER FILES FROM DESKTOP TO LAPTOP
Echo 3. EXIT THE PROGRAM
echo.
set /p choice=Enter Number:
if '%choice%'=='2' goto _desktopToLaptop
if '%choice%'=='3' goto :EOF
echo "%choice%" is not a valid option. Please try again
echo.
goto _start
:: Detect Drive Letters
:_desktopToLaptop
setlocal EnableDelayedExpansion
FOR /F "usebackq skip=1" %%a IN (`WMIC logicaldisk where DeviceID^="%_driveID%" get caption`) DO (
SET _NetworkDrive=%%a
if exist %%a (
CALL :_backup
goto :EOF
) else (
echo.
echo The laptop does not appear to be attached to the computer.
echo.
pause
goto :EOF
)
)
:_backup
:: Detect the folder locations and begin to backup each location to the laptop.
FOR /F "tokens=4 skip=1" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
echo we are past the for loop
pause
:: Return to directory program was run from
popd

If anyone else runs into this issue or something similar, check your tokens and your skip. Mine worked just fine as a single batch but when I included as a call I had to change the options from tokens=4 skip=1 to tokens=3* skip=2 in order to get the correct output.
The correct tokens in that FOR LOOPS should be:
#echo off
:: Set Variables
SET _driveID=T:
SET _params=/Z /E /COPY:DT /R:1 /W:0 /XD LocalService NetworkService temp "temporary internet files" winsxs Content.IE5 cache /XF ntuser.* *.tmp /XJ /FP /NC /NS /NP /NJH
SET _regshell=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
SET _regdesktop=Desktop
:: Set Current Directory
pushd %SystemDrive%\
:: Start Menu - Create Choices and Options. Send to various places to perform the actions.
:_start
cls
ECHO Please type either option 2 or 3 and then press ENTER on the keyboard?
Echo 2. TRANSFER FILES FROM DESKTOP TO LAPTOP
Echo 3. EXIT THE PROGRAM
echo.
set /p choice=Enter Number:
if '%choice%'=='2' goto _desktopToLaptop
if '%choice%'=='3' goto :EOF
echo "%choice%" is not a valid option. Please try again
echo.
goto _start
:: Detect Drive Letters
:_desktopToLaptop
setlocal EnableDelayedExpansion
FOR /F "usebackq skip=1" %%a IN (`WMIC logicaldisk where DeviceID^="%_driveID%" get caption`) DO (
SET _NetworkDrive=%%a
if exist %%a (
CALL :_backup
goto :EOF
) else (
echo.
echo The laptop does not appear to be attached to the computer.
echo.
pause
goto :EOF
)
)
:_backup
:: Detect the folder locations and begin to backup each location to the laptop.
FOR /F "tokens=3* skip=2" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
echo we are past the for loop
pause
:: Return to directory program was run from
popd

Given that the main issue in your script appears to be the setting of a variable to the data within the defined registry key and value, you could use:
Set "_regshell=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
Set "_regdesktop=Desktop"
Set "_dt="
For /F "EOL=H Tokens=2*" %%A In ('Reg Query "%_regshell%" /V "%_regdesktop%"'
) Do Set "_dt=%%~B"
If Not Defined _dt GoTo :EOF
Echo "%_dt%"

Related

List Directory and number of files with specific extension, build a specific menu

I am trying to create a menu with submenus which their names without extension come from the directory. However, I am unable to make a variable for choice as number. This code does not work anyhow. I would also want to display a number at the beginning of each file name in the menu; in fact, number of the files will also be one of the number that user selects as input. I could not overcome the problem.
#echo off
cd C:\Users\Murray\Documents\ConfigFiles\
for /f %%A in ('dir /a-d-s-h /b *conf ^| find /v /c ""') do set count=%%A
echo File count = %count%
for %%F in ("C:\Users\Murray\Documents\ConfigFiles\*.conf") do echo %%~nxF
set choice=
set /C /N="Please choice: "
if "%choice%" == "%count%" goto SUBMENU
if NOT EXIST "C:\Users\Murray\Documents\ConfigFiles\%choice%" goto NOFILE
:SUBMENU
Echo You are here
goto end
:NOFILE
echo %choice% could not be found.
goto END
:end
Any help will be appreciated.
Here's a quick example of a method touted in the answer by on no. It will print a number to the screen followed by the names of each file matching file extension, so will allow a large number of matching files, (although the end user may have to scroll a long list). Once a file is chosen, your end user then just types its corresponding number. The code should not proceed beyond the input request until a number matching one in the list is ENTERed.
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "src=C:\Users\Murray\Documents\ConfigFiles"
Set "ext=.config"
If Not Exist "%src%\*%ext%" Echo No file matches.& GoTo End
For /F "Delims==" %%G In ('"(Set #) 2>NUL"') Do Set "%%G="
For /F "Delims==" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe OS Call /? ^|
%SystemRoot%\System32\find.exe "=="') Do Set "HT=%%G"
For /F "Tokens=1* Delims=:" %%G In ('Dir /B /A:-D "%src%\*%ext%" 2^>NUL ^|
%SystemRoot%\System32\findstr.exe /E /I /L /N "%ext%"'
) Do Set "#%%G=%%H" & Echo( %%G.%HT:~-1%%%H
If Not Defined #1 Echo No file matches.& GoTo End
:Opt
Echo(
Set "HT=" & Set "opt="
Set /P "opt=Enter the number for your chosen file>"
If Not Defined opt (GoTo Opt) Else Set "opt=%opt:"=%"
Set # | %SystemRoot%\System32\findstr.exe /B /L "#%opt%=" 1>NUL || GoTo Opt
SetLocal EnableDelayedExpansion
For %%G In ("!#%opt%!") Do EndLocal & Set "opt=%%~G"
#Rem Your code goes below here
Echo(& Echo You Selected %opt%
#Rem Your code ends above here
:End
Setlocal EnableDelayedExpansion & For /F "Tokens=1,2" %%G In ("!CMDCMDLINE!"
) Do Endlocal & If /I "%%~nG" == "cmd" If /I "%%~H" == "/c" Echo(& Echo Press^
any key to exit.&Pause 1>NUL
All you need to do is to modify the variables values on lines 4 and 5, if necessary, in order to test it. I will not be supporting changes or additions beyond that. Once you have tested the code, you may insert your code between lines 25 and 29, replacing the example line I left there for your test.
Batch's limitations are to blame for sub-par corrections to this question.
Here's the best I could whip up in a few seconds:
#echo off
:one
cls
cd C:\Users\Murray\Documents\ConfigFiles\
for %%F in ("C:\Users\Murray\Documents\ConfigFiles\*.conf") do echo %%~nxF
echo.
echo Enter Configuration Name:
set/p "prompt=>"
if exist %prompt%.txt goto :two
if exist %prompt% goto :two
cls
echo File not found
pause >NUL
goto :one
:two
cls
REM When file is found, this code will run
pause >NUL
The set command does not prompt for user input unless specified with the /p switch. To make your code more friendly, i'd also recommend to prompt for the filepath earlier on in the code.
EDIT: A few alternative solutions: Declare the 9th option of the prompt of the choice command as a "second page" or "more" option. This would really be a pain for the user in a directory with tens or hundreds of files. Another; you can assign an integer to each file that matches your quasi-query and echo them before each filename on the screen, then allow the user to input the number to get that file. That seems fairly efficient, and if you'd like to explore one or both of those alternates I can help (if you need it).

batch to display folders to select from, user selects folder, then it copies that folder to another folder

So what I'm trying to do is, i have a bat file that makes timestamped backups(for example, 180126_053327 in the format: yymmdd_hhmmss). I'm trying to create this bat to add to it, so i can have it lookup those backups, display in console to allow the user to select the backup they want to restore by inputting the number they want and then copy it to a location.
so far what i have creates this:
Pic of what I have so far
The pic above is from the following script:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set i=0
For /f %%a in ('dir I:\AM_Configs-backups\ /B /A /D') do (
set /a i+=1
echo !i! %%a
set dir!i!=%%a
)
echo.
set /p uin="Select a directory [1-!i!]: "
set udir=!dir%uin%!
echo Selected - %udir%
md c:\test2
copy %udir% c:\test2
#PAUSE
I keep getting this:
Select a directory [1-29]: 27
Selected - 180126_053327
The system cannot find the file specified.
Press any key to continue . . .
I got the script above from this link: Prompting user to select directory in batch file
It cannot be found because %udir% is not in the current directory. This means that your base directory, I:\AM_Configs-backups, needs to be pre-fixed to your Copy command.
Copy "I:\AM_Configs-backups\%udir%" "C:\test2"
Also here is an alternative to the linked example you provided in your question:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
If Not Exist "C:\test2\" MD "C:\test2"
Copy "%dir[X]%" "C:\test2"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"
You can adjust your base directory on line 3 and put your own commands from line 9 onwards, (up to the Exit /B).
You should consider using RoboCopy for copying directories!
Edit
For the XCopy version, you'd probably need to change to:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
XCopy "%baseDir%\%dir[X]%" "%AppData%\Awesomeminer\%dir[X]%" /S /I /F /Y 2>Nul
Echo Starting Awesome Miner...
Start "" "%ProgramFiles(x86)%\Awesome Miner\AwesomeMiner.exe"
Pause
Call "Switch-N-Bkup.bat"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=!dir[%dir[X]%]!"
For the RoboCopy version you'd change line 11 to:
RoboCopy "%baseDir%\%dir[X]%" "C:\test2\%dir[X]%" /S 2>Nul
...plus any additional switches you may need
I ended up using this cus i have another batch for switching and backing up:
to kinda give you an idea, i have a primary bat for switching and copying configs, which will start teh program automatically after their copied. in that bat i also have code for backing up current configs to a location using time/date and creates the folders in this format: yymmdd_hhmmss...i needed an easy restore function, which with the link and code you provided helped with the user able to select which folder to restore and copying it to the programs data folder to be used, then auto-starting the program using the copied config.
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
REM If Not Exist "C:\test2\" MD "C:\test2"
xcopy "%dir[X]%" "%USERPROFILE%\AppData\Roaming\Awesomeminer\" /S /F /R /Y
START C:\"Program Files (x86)"\"Awesome Miner"\AwesomeMiner.exe
ECHO Starting Awesome Miner...
#Pause
CALL Switch-N-Bkup.bat
exit /b
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"

net use - Causing Echo Redirect to Fail

I have a script that successfully scans a specified directory for a list of files, copies the files to a destination folder and generates a log of all files not found in the source. I had to alter this script to include net use in order to map a network drive. Since doing so the script no longer generates the error log as it did before.
I'm very new to this and can't find any information on why this may be happening. Can somebody please help?
#echo off
pause
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
net use U: \\abc\def
SET "src="U:\Source Folder""
SET "dst=C:\Destination Folder"
SET "file_list=C:\files.txt"
SET "out=.\errors.log"
echo > %out%
FOR /F "usebackq eol=| delims=" %%f IN ("%file_list%") DO (
rem just searching to find out existense of file
WHERE /Q /R %src% "%%f"
IF "!ERRORLEVEL!" == "0" (
FOR /F "usebackq eol=| delims=" %%s IN (`WHERE /R %src% "%%f"`) DO (
echo "%%s => %dst%\%%f" >> %out%
#copy /y "%%s" "%dst%\%%f"
)
) ELSE (
echo %%f >> %out%
)
)
Replace echo %%f >> %out% with set /p out=%%f
[Edit]
Sorry I misunderstood your question.
Is it because you have two quotation marks in all of the drive path set?
As in replace
SET "src="U:\Source Folder""
With
SET src="U:\Source Folder"

How to sort the arguments dropped to a batch file?

I am writing a batch file that finds and executes all update.bat file inside all the directories dropped onto it.
The problem here is that I expect the arguments (i.e directories' path) comes in ordered by name but it turns out they are sorted by the modified date.
Is this the default behavior of Windows (Windows 7)? Any suggestion to solve this?
Here is my batch script:
#echo off
Setlocal EnableDelayedExpansion
if [%1]==[] goto :no_update_dropped
set LOG_FILE=update_log.txt
echo You are about to run these updates:
for %%G IN (%*) do (
if exist %%~sG\NUL echo %%G
)
pause
for %%G IN (%*) do (
if exist %%G\NUL (
if exist %%G\update.bat (
call %%G\update.bat %LOG_FILE%
) else (
echo No update.bat found in %%G.
goto :no_batch_found
)
)
)
goto :success
:no_update_dropped
echo NO UPDATE FOLDER FOUND
echo Drag and drop one or more update folder to run.
goto :exit
:no_batch_found
echo UPDATE NOT COMPLETED!
goto exit
:success
echo all updated has been run successfully
goto :exit
:exit
pause
Best Regards.
You can sort your argument list right in your for loop like this:
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('(for %%i in (%*^) do #echo %%~i^)^|sort') do (
set dirname=%%a
set dirname=!dirname:~0,-1!
echo use "!dirname!" without the trailing space
)
P.S. It seems like sort appends a space to the end of string,(WTF ????) so you'll have to get rid of it. I changed the code.
Finally with the help of dbenham's explanation this becomes:
for /f "delims=" %%a in ('cmd /c "for %%i in (%*) do #echo %%~i"^|sort') do (
echo use "%%a"
)
P.P.S This should work safer with commas in names (of course, they must be quoted)
for /f "delims=" %%a in ('cmd /c ^"for %%i in ^(%*^) do #echo %%~i^"^|sort') do (
echo use "%%a"
)
I would change the input set.
You can order by name by using /on and to get directories
/ad
so all directories by name =
dir /ad /on

Remotely check file size and get report

This script tries to:
get an input from a txt file, which is a list of computer names,
check if a log file on a computer from the list is bigger than 1000 bytes,
create a txt report with the names of those computers where the log file is more than 1000 bytes,
create another txt report with the names of the computers where the file is less than 1000 bytes.
However, something goes wrong. Any help could be nice.
#echo off
for /f "tokens=*" %%I in (computernames.txt)do call :checksz %%I
goto :eof
:checksz
setlocal
set file="\\%1\c$\data\info.log"
set min=1000
FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA
if %size% GTQ %min% (
echo. %1 >>logsizemin.txt
) ELSE (
echo. %1>>logsizemax.txt
)
Hello everyone,
thanks for your valuable support. I congratulate whith those who conceived and built this site is really well done and useful.
I made some modifications to the script that you have kindly suggested to incorporate other features, but something is not working as I would like .. as you can view I use editv32 in order to hide password in my batch, the principle is the same but as you can see after checking the size of the log, "maxlongsize.txt" is used in order to take the names of the PCs on which do the next activity. I wish that the activities were performed sequentially on all PCs in the file "logsizemax.txt" with only one authentication at the beginning. I noticed that, for some reason sometimes the file "logsizemin.txt" is not created but i don't understand why. The maximum would be to put in another file such as "computer unreachable" those PCs that are not reached on the network but I have absolutely no idea how implement it. I hope I have sufficiently explained. Sorry for bad English! I think you understand my intention :). Following the batch
#setlocal
#echo off
editv32 -p "Enter username:" USR
editv32 -m -p "Enter password:" PWD
for /f "tokens=1" %%I in (computernames.txt) do call :checksz %%I
endlocal
goto :eof
:checksz
setlocal
set file="\\%1\c$\data\data.log"
set min=1000
type NUL>logsizemax.txt
type NUL>logsizemin.txt
if not exist %file% goto :eof
FOR /F "usebackq delims=" %%A IN ('%file%') DO set size=%%~zA
if %size% GEQ %min% ( echo %1>>logsizemax.txt ) ELSE ( echo %1>>logsizemin.txt )
endlocal
#setlocal
for /f "tokens=1" %%I in (logsizemax.txt) do call :sw %%I
endlocal
goto :eof
:sw
echo.
echo *****************************************
echo * VBS & Deploy script *
echo *****************************************
echo.
echo Run VBS and deploy script .....
psexec \\%1 -u %USR% -p %PWD% cscript "\\rep\Reg.vbs"
psexec \\%1 -u %USR% -p %PWD% cmd /c "\\rep\deploy.cmd"
echo.
echo **************************
echo * EXE Run *
echo **************************
echo.
echo Running exe .....
psexec -u %USR% -p %PWD% \\%1 "c:\Program Files\test.exe"
echo.
echo ***********************************
echo * Exe application launched *
echo ***********************************
echo.
goto END
:END
exit
You can avoid using environment variables and using the second FOR alltogether. Try this simpler version of your bat, with a more generic :checksz routine.
#echo off
for /f "tokens=*" %%a in (computernames.txt) do (
call :checksz "\\%%a\c$\data\info.log" 1000 "%%a"
)
goto :eof
:checksz
if %~z1 GTR %2 (
echo %~3 >> logsizemin.txt
) ELSE (
echo %~3 >> logsizemax.txt
)
goto :eof
see HELP CALL for more information.
Changes: GTG->GEQ, don't surround variable with quotes twice, remove leading space from echo, and a little clean up.
#setlocal
#echo off
for /f "tokens=1" %%I in (computernames.txt) do call :checksz %%I
endlocal
goto :eof
:checksz
setlocal
set file=\\%1\c$\data\info.log
set min=1000
if not exist %file% endlocal && goto :eof
FOR /F "usebackq delims=" %%A IN ('%file%') DO set size=%%~zA
if %size% GEQ %min% ( echo %1>>logsizemin.txt ) ELSE ( echo %1>>logsizemax.txt )
endlocal
goto :eof
edit: updated per comments from PA and Andriy M - endlocal if the file doesn't exist, and remove \ update note.

Resources