Batch - display folder names as options - windows

I'm trying to create a small batch file which reads a folder (path is set as a variable in the file). It should display the names of all sub-folders as choices for the user and when the user chooses one that folder name should be saved in a variable for later use. The idea is that I have alot of branches I'm working on and in all of them there is a little jar file I want to run with this batch. So the batch present me a list of all branches in the folder and when I pick on it will start the jar file located in that branch folder.
EXAMPLE:
C:\code
contains
C:\code\branch1
C:\code\branch2
C:\code\branch3
Then I want the batch to present the following menu to the user:
1. branch1
2. branch2
3. branch3
When the user has chosen the folder name (f.ex. branch2) is saved in a variable for later use.
I've tried alot of googling, but nothing helpful came up. Sofar I've managed to read the sub-folders' names, but I dont know where to go from here.. can anyone point me in the right direction?

We first need delayed expansion
setlocal enabledelayedexpansion
Then need a list of all subfolders (assuming %dir% being set to the directory you want subfolders of):
set Index=1
for /d %%D in (%dir%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
Then you can present a choice (I added a little input validation, but it's not enough):
for /l %%i in (1,1,%UBound%) do echo %%i. !Subfolders[%%i]!
:choiceloop
set /p Choice=Your choice:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
Then you can set a variable with the subfolder the user chose:
set Subfolder=!Subfolders[%Choice%]!

Related

How to Write a batch script for checking mulitple folders and folder inside a folder and set the csv files to variables?

I have to write a batch script to go inside multiple folders and folder inside a folder and set the CSV files inside it and set it to a variable.
my folder structure is
c:\data\client1\data1.csv
c:\data\client1\data2.csv
c:\data\client1\config\env.csv
c:\data\client2\data1.csv
c:\data\client2\data2.csv
c:\data\client2\config\env.csv
so like these I have many clients folder with config folder inside it and some data CSV's
now I have to use some loops to go inside "c:\data\" and check the client1 folder and inside I need to set var = data1.csv and var = data2.csv using for loop then I need to go inside config folder and set envs= env.csv (i.e the file name or path of the files)
I have tried a code but I am not getting the correct login on how to search and loop inside.
#ECHO OFF & setlocal EnableDelayedExpansion
CD "C:\data"
For /R %%A in (*.csv) DO (
Set "file[!#!]=%%A"
Set /A #+=1
)
For /L %%B in (0,1,!#!) do Echo(!file[%%B]!
I modified the code as per the solution. But now I am unable to set the data1.csv in the client1 folder. and Can anyone explain this code?
Can anyone help me with the logic of the coding part?
output is :
c:\data\client1\data2.csv
c:\data\client1\config\env.csv
c:\data\client2\data1.csv
c:\data\client2\data2.csv
c:\data\client2\config\env.csv
You can do the following to assign them to an indexed variable.
With even moderately large file sets, a singular variable would exceed the line capacity, losing information assigned to it.
#ECHO OFF & setlocal EnableDelayedExpansion
CD "C:\data\client"
For /R %%A in (*.csv) DO (
Set "file[!#!]=%%A"
Set /A #+=1
)
For /L %%B in (0,1,!#!) do Echo(!file[%%B]!

How do you create a menu populated with directory names and selectable by position in a batch file?

Firstly I would like to say that it has been 10 years since I dabbled in programming and my memory of what I have learnt seems to be failing me. I hope I have included enough info for people to see what I am trying to do without going to extremes. There may be better ways to do what I have done and any suggestions will be appreciated.
I have 2 batch files, both in the parent directory, 1 to back up files in 2 sub directories of the parent directory to another sub directory a few levels down from the parent directory.
eg.
The batch files are in the directory "Test Folder"
The files to be backed up are in the location :-
Test Folder\LocalProfiles
and
Test Folder\SavedLocal
The folder where they are to be backed up to is called "Backup" with created directories using a name chosen by the users eg. "Blue" and then in another directory under that using the current Date and Time as the name of the directory, followed by the original directory. (The format of the date and time, currently 2016-04-06 23.03.15 has not been finalised as the space that I am using in the backup batch file between the date and time has been giving me problems in this batch file when restoring). So the location of the files for this user that have been backed up would be:-
Test Folder\Backup\Blue\2016-04-06 23.03.15\LocalProfiles
and
Test Folder\Backup\Blue\2016-04-06 23.03.15\SavedLocal
I have written a batch file that lists all of the user chosen directories
1st Screen
then after the user chooses a directory they then choose a directory from the directories labeled with a date and time
2nd Screen
and then it copies the files below back to the original location.
The problem with this is that it takes time and can lead to typos, especially when putting in the date and time. I wanted to make it as fool proof as possible by creating a menu where the user can select a number corresponding with a user created directory.
The end result would be:-
1st menu screen
Select one of the following
1. Blue
2. Red
3. Green
etc.
and then display the directories with dates and times that are contained in the selected directory on the next menu screen.
2nd Menu
Select one of the following
1. 2016-04-05 21.03.28
2. 2016-04-05 21.05.51
3. 2016-04-06 23.00.14
etc.
The user would simply type the number corresponding to the selected directory and press enter.
In the end I would like to merge both batch files with a choice to backup or restore but I need this to work properly first.
The following is the code for restoring the files, without the use of menus. It works but it doesn't always handle spaces in directory names and I'm sure there would be a better way to handle the error checking and messages.
#echo off
if not defined in_subprocess (cmd /k set in_subprocess=y ^& %0 %*) & exit )
:Prompt for Profile Name
cls
echo.
echo Please select one of the following Profiles to load.
echo.
:: Create the list of Profiles from the Directory Names
for /d %%D in (.\Backup\*) do echo %%~nxD
echo.
:: Prompt for Profile Name for multiple Profile Names
set "profile="
set /p profile=Please enter a Profile Name.
:: OR
:: Consider adding Fixed Profile Name to top of list/menu as the default for quick saving of files.
:: set "profile=Default"
:: Check that the Profile exists
echo.
if not exist ".\Backup\%profile%" echo The Profile %profile% does not exist.
if not exist ".\Backup\%profile%" pause
if [%profile%] == [] echo A Profile must have a name.
if [%profile%] == [] pause
:: If input is empty or doesn't exist return to the beginning.
if not exist ".\Backup\%profile%" goto Prompt for Profile Name
if [%profile%] == [] goto Prompt for Profile Name
:Saved
:: Create the list of Saved locations from the Directory Names
cls
echo.
echo Existing Saved Locations for the Profile named %profile%
echo.
for /d %%S in (".\Backup\%profile%\*") do echo %%~nxS
:: Prompt for Saved location for selected Profile Name
set "save="
echo.
set /p save=Please enter a Saved location.
:: Check that the Saved Location exists
echo.
if not exist ".\Backup\%profile%\%save%" echo The Saved Location %profile%\"%save%" does not exist.
if not exist ".\Backup\%profile%\%save%" echo Select a Saved Location from the list.
if not exist ".\Backup\%profile%\%save%" pause
:: Check that the Saved Location is not empty
if [%save%] == [] echo Select a Saved Location from the list.
if [%save%] == [] pause
:: If input is empty or doesn't exist return to the beginning.
if not exist ".\Backup\%profile%\%save%" goto Saved
if [%save%] == [] goto Saved
:: Check for Saved files
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo LocalData.profile for %profile% does not exist at location "%save%\LocalProfiles\"
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo LocalMember.profile for %profile% does not exist at "%save%\SavedLocal\"
:: If LocalData.profile doesn't exist display message and return to Saves.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo The Save at %save% is incomplete or does not exist.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" echo Please select another Save.
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" Pause
if not exist ".\Backup\%profile%\%save%\LocalProfiles\LocalData.profile" goto Saved
:: If LocalMember.profile doesn't exist display message and return to Saves.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo The Save at %save% is incomplete or does not exist.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" echo Please select another Save.
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" Pause
if not exist ".\Backup\%profile%\%save%\SavedLocal\LocalMember.profile" goto Saved
:Load Save
:: Restore the valid Save to the original location.
echo.
echo Restoring Saved Files
robocopy ".\Backup\%profile%\%Save%\LocalProfiles" ".\LocalProfiles"
robocopy ".\Backup\%profile%\%Save%\SavedLocal" ".\SavedLocal"
echo.
echo Files Restored
pause
exit
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "directories=localprofiles savedlocal"
CALL :zap$
:: First menu
CALL :choose blue default green red "white and puce stripes" /now
SET "userchosenname=%$choice%"
:: Don't know what format you are using for date and time.
:: I use dd/mm/yyyy and hh:mm:ss.hh
SET "backupdatestamp=%date:~-4%-%date:~3,2%-%date:~0,2% %time::=.%"
SET "backupdatestamp=%backupdatestamp:~0,-3%"
CALL :choose "backup as %backupdatestamp%"
FOR /f "delims=" %%a IN ('dir /b /ad "%sourcedir%\%userchosenname%\" 2^>nul') DO (
IF EXIST "%sourcedir%\%userchosenname%\%%a\localprofiles\." CALL :choose "restore from %%a"
)
CALL :choose /now "With this prompt"
FOR %%a IN (%directories%) DO (
IF "%$choice:~0,6%"=="backup" (
ECHO(MD "%sourcedir%\%userchosenname%\%backupdatestamp%\%%a"
ECHO(XCOPY /s/e "%sourcedir%\%%a" "%sourcedir%\%userchosenname%\%backupdatestamp%\%%a\"
) ELSE (
ECHO(XCOPY /s/e "%sourcedir%\%userchosenname%\%$choice:~13%\%%a\*" "%sourcedir%\%%a\"
)
)
GOTO :EOF
:: remove variables starting $
:ZAP$
FOR /F "delims==" %%Z In ('set $ 2^>Nul') DO SET "%%Z="
GOTO :EOF
:: Make a choice
:: If a parameter is '/now' actually make a choice with prompt next-parameter
:: else accumulate choices
:choose
SET "$item=%~1"
IF NOT DEFINED $item GOTO :EOF
IF /i "%$item%"=="/now" GOTO makechoice
IF NOT DEFINED $options cls
IF NOT DEFINED $choices SET "$choices=123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SET "$options=%$options%%$choices:~0,1%"
SET "$choices=%$choices:~1%"
SET /a $optioncount+=1
SET "$option%$optioncount%=%~1"
ECHO(%$options:~-1% %~1
SHIFT
GOTO choose
:makechoice
IF "%~2" neq "" SET "$options=%$options% /m "%~2""
choice /c %$options%
CALL SET "$choice=%%$option%errorlevel%%%"
CALL :zap$&SET "$choice=%$choice%"
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)
The required XCOPY commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(XCOPY to XCOPY to actually copy the files. Append >nul to suppress report messages (eg. 1 file copied)
The basis of this routine is the :choose subroutine which accumulates options into $-variables. It can be run either with 1 or more parameters, optionally quoted (in case a parameter includes a space.)
If the parameter /now is found, the routine asks for a choice to be made from the options presented. If the /now parameter is followed by another, that following parameter is used as a prompt for choice.
The CALL :zap$&SET "$choice=%$choice%" line uses the same parsing trick used to export values from a setlocal/endlocal bracket
Beyond that, all you'd need to do is fix the setting of backupdatestamp using the batch substringing facilities explained in the documentation
set /?
from the prompt.

Batch file to generate n amount of folders

Hi I would like to create a batch file which makes n amount of folders and moves them to a specified dir. something like make folders {00001-00009} to put it bluntly. I don't want to manually put each number in and I would like to be able to exclude numbers as well.
so far I have tried this code below. I get the 5 folders made in C:\source\
and I am able to dictate how they are named to an extent, by changing j=5 to whatever integer, however sometimes the file makes folders from 00256-003372 instead of what I specified. this happens when I change j to j=256 and run the program.
echo off
cd C:\source\ :: I included this because for some reason folder 1 copied to root
SET /a j=1
:floop
IF %j%==5 GOTO END
md 00%j%
cd 00%j%
SET /a j=%j%+1
cd C:\source\
GOTO FLOOP
:end
The other way I did this was to manually input each number in a .bat file such as below. which works fine but I have to make a line for each folder.
md C:\Device_Numbers_Folder\00001
md C:\Device_Numbers_Folder\00002
P.S I named the dir file source because I am running a bunch of .bat files with CALL and this is the source part.
I think you want something like this:
#echo off
setlocal EnableDelayedExpansion
::CD "C:\source\"
::only change these three lines
set "start=1"
set "amount=5"
set "length=5"
set "exclude=4,5"
set "excluded=0"
FOR %%G IN (%exclude%) DO (set /a "excluded+=1")
set /a "last=%start%+%amount%+%excluded%"
for /l %%i in (%start%,1,%last%) do (
set "skip=0"
FOR %%G IN (%exclude%) DO (if "%%i"=="%%G" set "skip=1")
if !skip! equ 0 (
set "folderName=0000000000%%i"
set "folderName=!folderName:~-%length%!"
md "!folderName!"
)
)
In this start is the first number, amount is the amount of folder it needs to create, and length is the lenght of the names of the new files, so 1 with length 5 becomes 00001. Exclude is an comma seperated list of all the numbers not allowed

Renaming Files With Batch

I am new completely new to batch and have used Python, Java ect for about a year now. So as you can guess I dont know overly large amount.
I have been instructed by my employer to try and automate some tasks we do on a regular basis. This may sound like a stupid task that is easy to-do but it happens a lot and when talking to customers at the same time it get boring quick. The task: Renaming multiple folders... We do this when end users have forgotten their password or need a profile reset.
The code that I have at the moment is:
:again
#echo off
set /p answer= Rename a file/folder(Y/N)?
if /i "%answer:~,1%" EQU "Y" goto yes
if /i "%answer:~,1%" EQU "N" goto no
goto again
:yes
set /p dirOfFile = Directory of file:
set /p currentFolder = Name of folder to be re-named:
set /p newFolder = What will it be re-named to:
ren %dirOfFile%\%currentFolder% %newFolder%
:no
exit
The code is based off of a few sources, the Y/N and using variable from other StackOverflow posts and the ren %dirOfFile%\%currentFolder% %newFolder% from the cmd command of ren or rename.
When I use:
ren C:\Users\Zak\Desktop\TestFolder AlsoTest
It renames a folder on my desktop from TestFolder to AlsoTest. This is what I want the batch file todo, but once its working, on multiple folders.
Thanks for any/all help!
you don't have a parameter %dirOfFile%. But you have a parameter named %dirOfFile<space>%
Same with you other variables.
Write your setcommand without spaces:
set variable=value
for example:
set /p dirOfFile=Directory of file:
Simple You can rename any File with Batch
type the following in batch file
ren "oldfile.txt" "newfile.txt"

batch file to move and rename folder to a relative path

I have the following batch file in Windows 7 to be executed by a context menu shortcut. My aim is to move and rename a quote folder containing subfolders and files to a different path and rename it with the project number inserted when prompted.
for %%Q in (.) do set quotenumber=%%~nQ
for %%Y in (.\..) do set year=%%~nY
for %%C in (.\..\..\..) do set client=%%~nC
set /P projectnumber="Enter Project number>"
move "c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber%" "c:\myfiles\mainfiles\clients\%client%\projects\%year%\%projectnumber%"
I get the error "the process does not have access to the file because it is being used by another process".
Can anybody tell me what I am doing wrong? I am not a programmer and cannot get this to work!
Any help would be greatly appreciated.
Looking at your code I'm assuming that you;re executing it in c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber% dir.
And in the last line you try to move the same dir to another place.Which is impossible because the dir is held by the script itself.Try this:
for %%Q in (.) do set quotenumber=%%~nQ
for %%Y in (.\..) do set year=%%~nY
for %%C in (.\..\..\..) do set client=%%~nC
set /P projectnumber="Enter Project number>"
cd ..
move "c:\myfiles\mainfiles\clients\%client%\quotes\%year%\%quotenumber%" "c:\myfiles\mainfiles\clients\%client%\projects\%year%\%projectnumber%"

Resources