Issue:
I am attempting to have users select which folder to choose from within a specified directory and then add that folder to the address in order to execute a program within that directory.
For example, !acct! is the variable that I am using to ask the end user which account they want to access. This account is the starting or root folder for all other folders. The folder structure remains that same across all accounts EXCEPT for the second token of the folder. i.e) 123456789\*\program\setup\
The * is the folder where multiple folders exist that I would like the end user to choose from.
Once chosen, I would like the script to add that directory so that the program could be executed.
I thought by setting the variable acctDir=C:\Users\jdoe\Desktop\!acct!\ would allow me to add the acct number for the root directory, then run a FOR loop that would allow me to use a wild card in the set for /d %%i in ( !acctdir!*media1\setup ) do ( start !app! )
Any help would be greatly appreciated!
#echo off
setlocal enabledelayedexpansion
:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.
goto :main
:main
setlocal
set /P acct=Please type the 9 digit account number you would like to restore:
set acctDir=C:\Users\jdoe\Desktop\!acct!\
set app=setup.exe /cd
set log=c:\logs.txt
echo. Starting on !date! !time! on !Computername! >> !log!
echo.
echo The account number you selected is: !acct!
echo.
goto :user
:user
set /p answer=Is this correct (Y/N)?
echo.
if /i !answer!==y goto :yes (
) else (
echo.
echo Ok. Let's try again^^!
echo.
Pause
cls
goto :beginning
)
)
:yes
for /d %%i in ( !acctdir!*media1\setup ) do (
start !app!
)
endlocal
goto :eof
You could try something like the following:
set c=0
For /f %%a in ('dir !acctDir! /B /A D') do (
set /a c+=1
echo !c! %%a
set dir!c!=%%a
)
echo.
set /p uin="Select a directory [1-!c!]: "
set udir=!dir%uin%!
echo Selected - %udir%
This loops through a directory listing of !acctDir! and prompts the user to select a directory based on the number assigned to it.
!acctDir!\%udir% will then be the location of the directory.
Related
How do I make a log file from this code. This has been answered a ton, but this file is huge and I want a simple log file. As you see I also tried to add a log file names RandomNamesLog.log. See if the output goes there.
I want all the code to be outputted into the log file, with error messages and confirm messages, like removing the #ECHO OFF value.
If you need more on what I want, please tell me.
#ECHO OFF
SETLOCAL EnableDelayedExpansion for /F "tokens=1,2 delims=#" %%a in
('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do ( set
"DEL=%%a" )
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
ECHO.
REM Randomly renames every file in a directory.
SETLOCAL EnableExtensions EnableDelayedExpansion
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET PrependOnly=0
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "__Translation.txt" is in the same
folder.
REM If you delete the translaction file, you will not be able to undo
the changes!
SET Undo=0
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET TranslationFile=_TranslatonData.txt
SET LogFile=_RandomNamesLog.log
IF NOT {%Undo%}=={1} (
REM Rename files
ECHO You are about to randomly rename every file in the following folder:
ECHO %~dp0
ECHO.
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
ECHO Type "OK" to continue.
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Aborting.
GOTO :EOF
)
ECHO Original Name/Random Name > %TranslationFile%
ECHO ------------------------- >> %TranslationFile%
FOR /F "tokens=*" %%A IN ('DIR /A:-D /B') DO (
IF NOT %%A==%~nx0 (
IF NOT %%A==%TranslationFile% (
SET Use=%%~xA
IF {%PrependOnly%}=={1} SET Use=_%%A
SET NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!
ECHO %%A/!NewName!>> %TranslationFile%
RENAME "%%A" "!NewName!"
ECHO ----------------------------------------------------- >> %TranslationFile%
ECHO Designed by Trevor T | UltimateGuidesPro.blogspot.com >> %TranslationFile%
ECHO. >> %TranslationFile%
ECHO WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING! THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION! >> %TranslationFile%
ECHO +---------+
ECHO | Credits |
ECHO +---------+
Echo.
ECHO Original Random Names script created by
call :colorEcho 0a "Jason Faulkner"
call :colorEcho 0a "HowToGeek.com"
ECHO ---------------------------------------
ECHO Script created by
call :colorEcho 0a "Trevor T"
ECHO -------------------------------------------
ECHO Color Text system created by
call :colorEcho 0a "Visual Magic, user on Stack Exchange"
ECHO Type "Exit" to quit
GOTO :Exit
:Exit
SET /P Confirm=
IF /I NOT {!Confirm!}=={Exit} (
ECHO.
ECHO Please try again
GOTO :Exit2
Exit
:Exit2
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Please try again
GOTO :Exit
)
)
)
) ELSE (
ECHO UNDO MODE
IF NOT EXIST %TranslationFile% (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
PAUSE
GOTO :EOF
)
ECHO Undoing...
FOR /F "skip=2 tokens=1,2 delims=/" %%A IN (%TranslationFile%) DO RENAME "%%B" "%%A"
DEL /F /Q %TranslationFile%
ECHO Completed Undo!
Pause
)
Exit
REM This is the color text code. Don't touch this, unless you know a better way to use color text.
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
I have rewritten your script fixing all of the problems I could see and removing the pointless code to add colored text.
Test it to see if it works as it should adding whatever you think I've missed.
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
REM Randomly renames every file in a directory.
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET "PrependOnly=0"
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "_TranslationData.txt" is in the same folder.
REM If you delete the translaction file, you will not be able to undo the changes!
SET "Undo=0"
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET "TranslationFile=_TranslationData.txt"
IF "%Undo%"=="1" GOTO UNDOIT
ECHO You are about to randomly rename every file in the following folder:
ECHO %CD%
ECHO.
CHOICE /M "Do you want to continue "
IF NOT %ERRORLEVEL%==1 (
ECHO.
ECHO Aborting.
TIMEOUT -1
GOTO :EOF
)
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
(
ECHO ;Original Name/Random Name
ECHO ;-------------------------
FOR %%A IN (*) DO IF NOT "%%A"=="%~nx0" IF NOT "%%A"=="%TranslationFile%" (
SET "Use=%%~xA"
IF "%PrependOnly%"=="1" SET "Use=_%%A"
SET "NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!"
ECHO %%A/!NewName!
REN "%%A" "!NewName!"
)
ECHO ;-----------------------------------------------------
ECHO ;Designed by Trevor T ^| UltimateGuidesPro.blogspot.com
ECHO.
ECHO ;WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING!
ECHO ; THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION!
)>"%TranslationFile%"
ECHO +---------+
ECHO ^| Credits ^|
ECHO +---------+
ECHO.
ECHO Original Random Names script created by Jason Faulkner # HowToGeek.com
ECHO -------------------------------------------
ECHO Script created by Trevor T
ECHO -------------------------------------------
TIMEOUT -1
GOTO :EOF
:UNDOIT
ECHO UNDO MODE
IF NOT EXIST "%TranslationFile%" (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
TIMEOUT -1
GOTO :EOF
)
ECHO Undoing...
FOR /F "USEBACKQ TOKENS=1-2 DELIMS=/" %%A IN ("%TranslationFile%") DO REN "%%B" "%%A"
DEL /F "%TranslationFile%"
ECHO Completed Undo!
TIMEOUT -1
GOTO :EOF
Once you are happy with it edit your opening question explaining what it is you want to have in the log file and how you need it to look.
I use this. it seems to work.
It just starts a log file and maintains logs.
You can set logpath and logname (base name) then you call this create_logfile
It creates a semi-random log file.
Now you write to the set logfile
I'm not an advanced coder. Please feel free to correct:
#echo off
rem
echo %date% %TIME%
rem Log File Path
if "%logpath%" == "" set logpath=%~dp0
if "%logpath:~-1%" == "\" set logpath=%logpath:~0,-1%
rem Make log file name
if "%logname%" == "" set logname=log
set t=%TIME: =0%
set d=%DATE%
set logfilename=%logname%_%d:~12,2%%d:~4,2%%d:~7,2%%t:~0,2%%t:~3,2%%t:~6,2%.log
set t=
set d=
rem Test
echo full log file name = %logfilename%
echo find base log name = %logfilename:~0,-17%
echo log path = %logpath%
rem Logs to maintain
set /a dellog=5
rem Find file to delete
set var=
set /a cnt=0
set fltodel=
set fstfle=
for %%a in (%logpath%\%logname%*.log) do (
set var=%%a
call set /a "cnt+=1"
echo %%cnt%%| findstr /l "1" >nul && (call set fstfle=%%var%%)
echo %%cnt%%| findstr /l "%dellog%" >nul && (call set fltodel=%%fstfle%%)
)
rem Delete old log
echo file to delete %fltodel%
if exist %fltodel% (del /q %fltodel%) else (echo "%fltodel%" does not exist. nothing to delete.)
echo tryed to delete
rem Create Log File and logfile attribute
set logfile=%logpath%\%logfilename%
if exist %logfile% (
echo start logging... "%~0" on %date% %time% >> %logfile%
) ELSE (
echo Start Log for "%~0" on %date% %time% > %logfile%
)
The point of this batch script is to take a user entered account number and replace the line in the text file containing that account number with something like "xxxxxxxxxxxxxxxxxxxxx". How would I go about doing that? Right now it is just displaying the account information of the account number.
set /p acct_code=Enter account code:
echo.
setlocal ENABLEDELAYEDEXPANSION
set flag=0
for /f "tokens=1-3 delims=," %%r in (accounts.txt) do (
if %%r==!acct_code! (
cls
echo Account Information
echo *******************
echo Account Code : %%r
echo Account Name : %%s
echo Account Balance : %%t
set flag=1
)
)
if !flag!==0 echo Account NOT Found, Please Try Again...
echo.
PAUSE
cls
you missed just the code to write the line again (to a new file):
...
for /f "tokens=1-3 delims=," %%r in (accounts.txt) do (
if %%r==!acct_code! (
cls
echo Account Information
echo *******************
echo Account Code : %%r
echo Account Name : %%s
echo Account Balance : %%t
echo(%r,%%s,%%t >>accounts.new
set flag=1
) else (
echo xxxxxxxxxxxxxxxxxxxxx>>accounts.new
)
)
ECHO move /y accounts.new accounts.txt
...
(Note: to actually rename the new file (overwrite the original file), remove the ECHO before move)
I'm making a game and I want a personalized username option that only appears once.
Here is an example:
#echo off
:onetime
echo please enter a username
echo.
set /p newuser=%newuser%:
echo %newuser%> cfg.txt
goto menu
:menu
for /f "tokens=* delims=" %%x in (cfg.txt) do echo %%x
cls
...
I'm trying to figure out how to make :onetime happen once, so that it sends the username to cfg.txt
Anyone know how?
I have cleaned up your code and provided a completed working script, and noted where you will put your game code.
Although Delayed expansion is not needed for this code, I have placed it in the script as you had it in your original script.
Please be mindful of the variable names I have chosen as they are used in several locations.
I have tried to comment the code with info on what it is doing, and I would be happen to explain further if needed.
I'd like to actually play your game when you are completed with it, if I may. :)
Hope that helps.
Ben
BPG.cmd
REM Script: BPG.cmd
REM Version: 1.0
REM Description: Game to play about Monsters.
Rem Notes: Currently Implementing Menu System.
Rem Sets up Variables and checks if the script needs to be re-called.
#(
SETLOCAL ENABLEDelayedExpansion
echo off
SET "eLvl=0"
SET "ScriptFolder=%~dp0"
SET "Log=%~dpn0.log"
SET "ConfigFile=%~dpn0_cfg.txt"
IF /I "%~1" NEQ "MAX" (
ENDLOCAL
ECHO.Game not started Maximized, Opening in a New Window by Running: Start "BPG 1 A Batch of Monsters" /MAX "%~dpnx0" MAX
Start "BPG 1 A Batch of Monsters" /MAX "%~dpnx0" MAX
EXIT /b %eLvl%
)
COLOR 2
)
REM Calls Main Function.
CALL :Main
REM Ends the script.
(
ENDLOCAL
EXIT /b %eLvl%
)
REM Main Function, most of your coding goes here, and this function calls sub functions.
:Main
Rem Check if Config file exists, if it does not, then call the New User Function.
IF NOT EXIST "%ConfigFile%" (
CALL :NewUser
)
Rem Load Username from Config file.
FOR /F "Tokens=*" %%A IN ('Type "%ConfigFile%"') DO (
SET "_UserName=%%~A"
)
Rem Call Menu System
CALL :Menu
REM Based off the option chosen Either Start a new Game or Skip to the End.
REM ECHO.CALL %_Menu_Choice%
CALL %_Menu_Choice%
GOTO :EOF
:NewUser
SETLOCAL
REM Get the Username Input
SET /P "_User=Please Enter a Username: "
REM Output the Username to the config file, overwriting all the file contents:
echo.%_User%>"%ConfigFile%"
ENDLOCAL
GOTO :EOF
:Menu
SETLOCAL
REM Output the Config file contents:
Type "%ConfigFile%"
REM Clear the screen
cls
echo ______ _______ _______
echo I ___ \ I ____ I I ____ \
echo I I I II I II I I \/
echo I I__/ / I I____II I I
echo I __ I I _____I I I ____
echo I I \ \ I I I I \_ I
echo I I___I II I I I___I I
echo I______/ I_/ I_______I A BATCH OF MONSTERS
echo.
echo.
echo 1) Begin
echo.
echo 2) Exit
echo.
set /p "_Choice=%_UserName%, Enter a Number: "
(
REM End the local variable Space, and Set return variables based on the choice, or re-draw the menu.
ENDLOCAL
IF /I "%_Choice%" EQU "1" (
REM ECHO.%_Choice% EQU 1
SET "_Menu_Choice=:Begin_Game"
) ELSE (
IF /I "%_Choice%" EQU "2" (
REM ECHO.%_Choice% EQU 2
SET "_Menu_Choice=GOTO :EOF"
) ELSE (
ECHO.%_Choice% Not Valid!
PAUSE
GOTO :Menu
)
)
)
goto :EOF
:Begin_Game
REM All the remaining code for your game should probably go here.
GOTO :EOF
try checking file existence :
#echo off
:onetime
setlocal enableDelayedExpansion
if not exist "cfg.txt" (
echo please enter a username
echo.
set /p newuser=%newuser%:
echo !newuser!> cfg.txt
goto menu
)
:menu
for /f "tokens=* delims=" %%x in (cfg.txt) do echo %%x
cls
Here is what I am attempting to do and if I can get your help it would be greatly appreciated!
Issue:
I want to create a script to do the following:
Go out to a network share where all account folders exist (2,400 folders with a 9-digit naming convention for account numbers, i.e folder name is 123456789).
Then go through a specific directory within the account folders that have a time stamp naming convention (i.e 123456789\Jan_29_2013_453pm).
Next, all folder structures are the same for all account folders EXCEPT the time stamped folder under the root (i.e 123456789`Jan_29_2013_453pm`\data).
Once being able to get through the time stamp folder there will be a set of folders that start off with a naming convention of media1, media2, media3, media4, media5, etc. that I need to access in order to move files.
I need to move a certain file from all media folders into media1. **There is an unknown amount of media folders for different account folders. Some may have 1 and other may have 50.
I need to run a test within the data folder (123456789\Jan_29_2013_453pm\data) to open a logfile.txt to see if a specific string exists at the end of the log (i.e item was successfully created as well as item has failed`).
If there is a SUCCESSFUL string in the logfile.txt, then go ahead and move all files from other media folders into media1. If a FAILURE string, then output the account folder name to a log file (output.txt) so I am aware which account folders failed (I would append the output as I will run this script multiple times).
The idea is to disregard account folders that have just a single media1 folder. Other account directories that have more than ONE media folder need to run a test against the log for SUCCESS or FAIL and depending on the string, to move a single file from all other media (media2,media3,media4,etc.) folders over to media1 unless FAILURE is read in the log.
I created a text file with all account folders on the share. I'm sure a FOR statement can be used against it. I'm also sure that a FOR statement can be used to go through the log in the "DATA" directory to look for the "SUCCESSFUL" or "FAILED" string.
The hard part I see is being able to get through the time stamped folder in order to get to the DATA directory.
THANKS AGAIN FOR ALL THE HELP!
#echo off
setlocal enabledelayedexpansion
:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.
echo Press ENTER to begin...
pause
echo.
goto :main
:main
cls
echo.
set /P acct=Please type the 9 digit account number you would like to restore:
set acctDir=X:\!acct!\
set acctDir2=media1\Setup\setup.exe /cd
set acctDir3=media1
set x=x:\!acct!\!userDir!
set sumLog="x:\!acct!\!userDir!\SummaryLog.txt"
set succ=finished
set log=c:\logs.txt
echo. Starting on !date! !time! on !Computername! >> !log!
echo.
echo The account number you selected is: !acct!
echo.
goto :user
:user
set /p answer=Is this correct (Y/N)?
echo.
if /i !answer!==y goto :yes (
) else (
echo.
echo Ok. Let's try again^^!
echo.
pause
cls
goto :main
)
)
:yes
set c=0
For /f %%a in ('dir !acctDir! /B /A:D') do (
set /a c+=1
echo !c! %%a
set dir!c!=%%a
)
echo.
set /p userIn="Select a directory [1-!c!]: "
set userDir=!dir%userIn%!
echo.
echo You selected !userDir! for your data retrieval.
echo.
goto :execute
:execute
echo.
echo The software will now be installed...
start !acctdir!\!userDir!\!acctDir2! >>!log!
:move
forfiles /p "!acctdir!\!userDir!\" /s /m *.ARC /c "cmd /c move #file !acctdir!\!userDir!\!acctdir3!"
goto
:string
findstr " .*!succ!" !sumLog!
if exist errorlevel 0 (
pause
goto :move
) else (
goto :eof
)
endlocal
goto :eof
#ECHO off
title Rename Script
set dir1=%1
set STR=%2
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
FOR %%n in (%dir1% *.*) DO (
ren %%n %STR%%%n
echo %STR%%%n)
echo done
pause
C:>yogesh>LDK.bat C:\yogesh app
OUTPUT:
Running Rename Script for STR=app
The syntax of the command is incorrect.
appC:\yogesh
appa3dapi.dll
appHLTV-Readme.txt
apphltv.cfg
appkver.kp
applanguage.inf
appLDR.bat
appMp3dec.asi
appMss32.dll
appMssv12.asi
appMssv29.asi
appTrackerNET.dll
The batch file cannot be found.
C:\yogesh>
There are few issues with this script:
" The syntax of the command is incorrect." I do not know where is the problem in script.
How to get the count of number of files renamed ?
Files get renamed into the directory where the .bat file resides I want to rename the files in specified folder as argument in variable dir1
Please let me know if you need more information.
Here is a solution without using CD. You needed to put a \ between your dir1 variable and *.* instead of a space. You needed quotes to protect against spaces in names. Use FOR variable modifiers ~nx to get just the name and extension (removes any drive and path info). Finally, use SET /A to perform math.
#ECHO off
title Rename Script
set "dir1=%~1"
set "STR=%~2"
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
set cnt=0
FOR %%F in ("%dir1%\*.*") DO (
ren "%%F" "%STR%%%~nxF"
echo %STR%%%~nxF
set /a cnt+=1
)
echo %cnt% files were renamed.
echo done
pause
Here you go:
#ECHO off
title Rename Script
set /A count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
set /p STR=choose a start-string:
echo Running Rename Script for STR=%STR%
FOR %%n in (*.*) DO (
ren "%%n" "%STR%%%n"
echo "%STR%%%n"
set /A count+=1)
echo count %count%
echo done
pause
we can save the current path in OLDDIR and then change the path to the one the user gave, at the end of the script we'll go back to OLDDIR using CD
you need to set the counter with /A
UPDATE for dbenham:
A small proof :)) that it worked (for me) with filenames that contains spaces: