I am trying to make a batch file that will assist with mapping a drive at startup
Basically it will write a batch file to the startup folder of the computer it is run on.
#Echo Off
cls
title Set Network drive 1.0
color 0A
rem "rem" is a message that can only bee seeing when editing a batch file. It will not be includded when running a batch file.
rem =====saving log file to your desktop==========
set log="%USERPROFILE%\Desktop\Set Network Drive 1.0.log"
echo.>>%log%
echo Starting log at %date% %time%>>%log%
echo.>>%log%
rem ==================Detecting OS type===========================
echo.
echo =====================Detection OS type=================
echo =====================Detection OS type=================>>%log%
echo.
echo.>>%log%
color 0c
echo One second please.......
echo.
for /f "tokens=2 delims=:" %%a in ('systeminfo ^| find "OS Name"') do set OS_Name=%%a
for /f "tokens=* delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
for /f "tokens=3 delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
rem ===========Setting OS type to use as variable %variable%=====
if "%os_name%"=="XP" set verssion=xp
if "%os_name%"=="7" set version=7
if "%version%"=="XP" set desktop=xp
if "%version%"=="7" set desktop=7
cls
color 0A
echo.
echo Operating system detected.............. Windows %version%
echo Operating system detected.............. Windows %version% >>%log%
echo.>>%log%
rem ===============Gathering information=========================
echo ===============Drive information==============>>%log%
echo.
echo.>>%log%
set /p driveletter=Drive letter to assign to:
echo Drive Letter................................ %driveletter%>>%log%
echo.>>%log%
echo.
set /p IP=Ip address device:
echo IP address of remote device................. %IP%>>%log%
echo.>>%log%
echo.
set /p path=Path on remote machine:
echo Path on remote machine set to............... %path% >>%log%
echo.>>%log%
echo.
set /p Username=Username (will be viewable in the log file and batch file):
echo Username.................................... %username%>>%log%
echo.
echo.>>%log%
set /p pass=Password (will be viewable in the batch file):
echo Password.................................... **********>>%log%
echo. >>%log%
echo ============================================================>>%log%
echo.>>%
rem ====================================================================
rem ====Writing batch file to startup folder as Map %driveletter%.bat===
rem ========windows 7==================
:win7
set startup="C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\Map %driveletter%.bat"
pause
echo #echo off >>%startup%
echo title Mapping network drive %driveletter%:>>%startup%
echo color 0A>>%startup%
echo cls>>%startup%
echo echo.>>%startup%
echo echo Wating for connection to drive location.........>>%startup%
echo goto loop>>%startup%
echo.>>%startup%
echo :loop>>%startup%
echo.>>%startup%
echo echo Pinging %ip%.........>>%startup%
echo cd c:\windows\system32\>>%startup%
THIS IS WHERE I HAVE THE PROBLEM. This command will not output to the batch file its creating and it shuts down this batch file
echo ping %ip% -n 1 | find "TTL">>%startup%
echo if not errorlevel 1 goto up>>%startup%
echo if errorlevel 1 goto loop>>%startup%
echo.>>%startup%
echo.>>%startup%
echo :up>>%startup%
echo cls>>%startup%
echo echo.>>%startup%
echo echo Device is up>>%startup%
echo echo.>>%startup%
echo echo Mapping drive......>>%startup%
echo c:\windows\system32\net use %driveletter%: \\%ip%\%path% %pass% /USER:%username% >>%startup%
echo if not errorlevel 1 goto up>>%startup%
echo if errorlevel 1 goto end>>%startup%
echo echo.>>%startup%
echo :end>>%startup%
echo echo Drive was mapped>>%startup%
echo echo.>>%startup%
rem ==========REMOVE THE FOLOWING LINE TO HAVE THE BATCH FILE GO AWAY WHEN COMPLETE======
echo pause>>%startup%
start notepad %log%
pause
#echo off
echo #echo off>t.bat
echo echo test complete>>t.bat
echo quit>>t.bat
This basically is a batch code which creates another batch file t.bat in the present working directory. You can direct the output file ( batch file created) to the startup folder using cd command. The >> operator echoes text to the next line of the output file.
Related
I have this script to send files to my ftp:
#echo off
#setlocal enableextensions
#cd /d "%~dp0"
color 0a
mode 34,12
title Enviar Vendas Eco
echo.
echo.
echo.
echo.
echo Sending ...
echo.
echo.
echo Wait ...
( echo open ftp.xxxxxxxxxxxxx.com
echo xxxxxxx
echo xxxxxx
echo ascii
echo prompt
echo cd "place1"
echo cd "place2"
echo lcd "%userprofile%\Desktop\test"
echo mput *.txt -overwrite
echo bye
)> %temp%\ftpsend.dat
ftp -s:%temp%/ftpsend.dat >nul 2>nul
del /f /s /q %temp%\ftpsend.dat >nul 2>nul
exit
By default, the script would must overwrite the files if already exists on .ftp. But it isn't happening.
What is wrong on my script?
When i run appears the file was suceffully transfered, but it didn't replace the file that already exists on ftp.
Look the image:
I am learning A LOT lately and have managed to get a basic bat file using script i have found online and mixing it all into one.
I have hit a small glitch where one of the lines now exports to a text file in the location the file is run from.
My issue now is that it autocloses after creating the text file rather than going back to the main start screen.
Can anyone help me out with this?
I have put the script that autocloses below for reference.
the final bit seems to close it (goto :eof) but if i remove that it stops exporting to the text file?
*Still to do - backup of pst files
title CMD Utility (C) Geoff Palmer Version 1.2
mode 48,40
#echo off
echo (C) Geoff Palmer Version 1.0
echo.
cls
goto start
rem ####################### START ######################
:start
echo (C) Geoff Palmer Version 1.2
echo.
mode 48,40
color 0f
#echo off
for /f "tokens=2*" %%a in ('net user "%Username%" /domain ^| find /i "Full Name"') do set DisplayName=%%b
echo %DisplayName% Welcome to the CMD utility (Beta)!!
echo What option would you like to execute?
echo.
echo NETWORKING:
echo _____________
echo 1) Ipconfig
echo 2) Reset Network
echo 3) Ping an ip address
echo 4) Trace Root
echo 5) NetStat
echo 6) Get Mac address
echo 7) Backup saved Wifi Networks
echo.
echo SYSTEM INFO:
echo ______________
echo 8) Who am I
echo 9) Uptime
echo 10) PC Info
echo 11) Performance Check
echo 12) Disk Check
echo 13) Driver Check
echo 14) Mirror Drive
echo 15) Recover Drive
echo.
echo WINDOWS TOOLS:
echo __________________
echo 16) Clear recycle bin and Temporary files
echo 17) Hard drive Defrag
echo 18) Start or End a Task
echo 19) Battery Performance
echo 20) Outlook Backup
echo.
echo Cleanup:
echo __________________
echo 21) Remove Battery Performance Log
echo 22) Remove Driver Log
echo.
echo 23) Exit
echo.
set option=
echo.
set /p option=Select One:
echo.
if "%option%"=="1" goto ipconfig
if "%option%"=="2" goto Network
if "%option%"=="3" goto ping
if "%option%"=="4" goto tracert
if "%option%"=="5" goto netstat
if "%option%"=="6" goto getmac
if "%option%"=="7" goto Wifi
if "%option%"=="8" goto whoami
if "%option%"=="9" goto uptime
if "%option%"=="10" goto pcinfo
if "%option%"=="11" goto perfmon
if "%option%"=="12" goto CHKDSK
if "%option%"=="13" goto DRIVER
if "%option%"=="14" goto MIR
if "%option%"=="15" goto recover
if "%option%"=="16" goto clearmgr
if "%option%"=="17" goto defrag
if "%option%"=="18" goto task
if "%option%"=="19" goto Power
if "%option%"=="20" goto pst
if "%option%"=="21" goto Cleanpwr
if "%option%"=="22" goto Cleandrv
if "%option%"=="23" goto Exit
echo.
ECHO “%option%” is not valid please try again
goto start
ECHO.
rem ###################### Options #####################
rem ###################### ipconfig #######################
:ipconfig
mode 70,40
cls
color 0c
echo.
ipconfig
pause
cls
goto start
rem ###################### Network #######################
:Network
mode 80,40
cls
color 0A
cls
ipconfig /release
ipconfig /renew
ipconfig /registerdns
goto start
rem ###################### ping #######################
:ping
cls
color 0b
#echo off
mode 45,2
color 0F
set /p a="Enter IP ADDRESS: "
MODE 60,15
ping %a%
echo [----------------------------------------------------------]
pause
cls
goto start
rem ###################### tracert #######################
:tracert
mode 60,5
cls
color 0b
echo Please enter web page you would like to trace?
echo [EXAMPLE] http://www.google.com
echo.
Set /p trace=
mode 75,50
echo.
echo Trace Root initiate
tracert %trace%
pause
cls
goto start
rem ###################### netstat #######################
:netstat
#echo off
color 0F
:options
mode 45,10
cls
echo MENU OPTIONS:
echo =====================
echo a All links
echo e Ethernet Statistics
echo f Displays FDQN
echo n Addresses and ports
echo =====================
echo q to quit
echo =====================
set /p input="Enter Options Here: "
if "%input%"=="a" goto:a
if "%input%"=="e" goto:e
if "%input%"=="f" goto:f
if "%input%"=="n" goto:n
if "%input%"=="q" goto:start
echo Please choose from the Options listed above!
pause
goto:options
:a
mode 80,60
netstat.exe -a
pause
goto:options
:e
mode 80,15
netstat.exe -e
pause
goto:options
:f
mode 80,25
netstat.exe -f
pause
goto:options
:n
mode 80,20
netstat.exe -n
pause
goto:options
rem ###################### getmac #######################
:getmac
mode 60,25
#echo off
cls
color 0e
echo.
arp -a
echo.
echo Have you got all the info needed?
pause
cls
goto start
rem ###################### Wifi #######################
:Wifi
mode 90,10
cls
echo This program will save all Wifi passwords on this computer to file then close.
pause
#echo off
setlocal enabledelayedexpansion
:main
title WiFiPasswordReveal v1.0b (c) Geoff Palmer
echo. >> results.txt
echo Reveal all saved WiFi passwords Batch file script v1.0b (c) Geoff Palmer >> results.txt
echo. >> results.txt
:: Get all the profiles
call :get-profiles r
:: For each profile, try to get the password
:main-next-profile
for /f "tokens=1* delims=," %%a in ("%r%") do (
call :get-profile-key "%%a" key
if "!key!" NEQ "" (
echo WiFi: [%%a] Password: [!key!] >> results.txt
)
set r=%%b
)
if "%r%" NEQ "" goto main-next-profile
echo. >> results.txt
goto :eof
::
:: Get the WiFi key of a given profile
:get-profile-key <1=profile-name> <2=out-profile-key>
setlocal
set result=
FOR /F "usebackq tokens=2 delims=:" %%a in (
`netsh wlan show profile name^="%~1" key^=clear ^| findstr /C:"Key Content"`) DO (
set result=%%a
set result=!result:~1!
)
(
endlocal
set %2=%result%
)
goto :eof
::
:: Get all network profiles (comma separated) into the result result-variable
:get-profiles <1=result-variable>
setlocal
set result=
FOR /F "usebackq tokens=2 delims=:" %%a in (
`netsh wlan show profiles ^| findstr /C:"All User Profile"`) DO (
set val=%%a
set val=!val:~1!
set result=%!val!,!result!
)
(
endlocal
set %1=%result:~0,-1%
)
goto :eof
goto start
rem ###################### whoami #######################
:whoami
mode 45,5
color 0d
whoami
pause
cls
goto start
rem ###################### uptime #######################
:uptime
mode 50,4
color 0d
systeminfo | find "System Boot Time:"
pause
cls
goto start
rem ###################### pcinfo #######################
:pcinfo
mode 80,60
cls
color 0e
systeminfo
pause
cls
goto start
rem ###################### perfmon #######################
:perfmon
mode 45,5
cls
color 0b
echo.
echo Please wait program starting!
PERFMON
pause
cls
goto start
rem ###################### CHKDSK#######################
:CHKDSK
mode 48,5
cls
echo Please enter the drive you would like to check?
echo.
Set /p DSK=
echo.
cls
echo Check disk initiate
CHKDSK %DSK%:
pause
cls
goto start
rem ###################### clearmgr#######################
:clearmgr
echo Just follow the On Screen instructions and Press OK, Press Delete and OK.
CleanMgr
echo DONE!!
pause
cls
goto start
rem ###################### defrag #######################
:defrag
echo You will need to run this program as Administrator
echo This will Defrag all volumes:
pause
defrag /C /H /V
pause
cls
goto start
rem ###################### DRIVER#######################
:DRIVER
mode 80,50
cls
echo Querying Drivers
echo Exporting to C Drive
driverquery /v /fo csv > "C:\driverlist.csv"
pause
C:\users\%username%\desktop\driverlist.csv
goto start
rem ###################### MIR #######################
:MIR
color 0c
echo Please Enter the Source DRIVE
echo.
set /p SOURCE=
echo Please Enter the Destination DRIVE
echo.
set /p DEST=
ROBOCOPY %SOURCE%: %DEST%: /MIR
pause
cls
goto start
rem ###################### recover #######################
:recover
echo Please Enter the Source file path
echo.
set /p SOURCE=
TYPE SOURCE
pause
cls
goto start
rem ###################### Power Check #######################
:Power
mode 80,10
cls
echo You will need to run this program as Administrator
echo.
echo This will save a battery report in the root hard drive
echo.
powercfg /batteryreport /output "C:\battery_report.html"
Pause
C:\battery_report.html
goto start
rem ###################### task #######################
:task
mode 40,10
cls
echo TASK KILL OR START TASK MENU
echo.
echo What option would you like to execute?
echo.
echo T) Tasklist
echo 1) Task Kill
echo 2) start task
echo 3) back
echo.
set option=
echo.
set /p option=Select One:
echo.
if "%option%"=="T" goto tasklist
if "%option%"=="1" goto taskkill
if "%option%"=="2" goto starttask
if "%option%"=="3" goto back
rem ################# tasklist ###################
:tasklist
mode 48,50
cls
echo The fowlling process are actives!
tasklist
pause
cls
goto task
rem ################# taskkill ###################
:taskkill
echo What process would you like to end?
echo.
set /p task_name= task name without .exe
taskkill /f /im %task_name%.exe
pause
cls
goto task
rem ################# starttask ###################
:starttask
echo What process would you like to start?
echo.
set /p task_name=
start %task_name%
cls
pause
goto task..
rem ################# back ###################
:back
cls
goto start
rem ###################### cleanpwr #######################
:Cleanpwr
cls
echo Removing Battery Performance Log
pause
del /f C:\battery_report.html
echo.
echo File Deleted!
pause
cls
goto start
rem ###################### cleandrv #######################
:Cleandrv
cls
echo Removing Driver List
pause
del /f C:\driverlist.csv
echo.
echo File Deleted!
pause
cls
goto start
rem ###################### PST #######################
:pst
mode 80,40
echo Format your USB stick you want to save PST files to as P
pause
cls
color 0a
robocopy "C:\users\%username%\appdata\local\Microsoft\Outlook" "P:\Backup" /mir
pause
cls
goto start
rem ###################### exit #######################
:exit
mode 45,5
cls
echo Are you sure you want to EXIT?
echo Select c to cancel or press ok to exit
set /p input="Enter Options Here: "
if "%input%"=="ok" goto:ok
if "%input%"=="c" goto:start
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%
)
I have a text file, a.txt:
Hello World
Good Afternoon
I have written a batch script to read contents of this file line by line:
FOR /F "tokens=* delims=" %%x in (a.txt) DO echo %%x
I am getting output as "Hello" "World" due to default behaviour of delimiter(space).
How can I override this behaviour to get the ouptut as "Hello World" "Good Afternoon"
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
#echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
#echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
About 3 days ago I asked a question, which can be found here:
how to replace a string on the second line in a text file using a batch file?
I'm converting the letters in a text file into their respective numbers. I'm getting error messages such as "Access denied" and "Cannot locate this file" -- but the same batch file that's giving me all these errors is also the one that made these text files to begin with! So it should be in the same directory as the batch file itself (unless specified otherwise), right? I even went to that folder and checked, and they're there.
I did add a small script to hide the files after they were created so that it wouldn't look so cluttered up. I did this by using
attrib +h C:\script\%name%.txt
Would hiding a file with this command make it invisible to batch programs that are searching for it/call upon it?
Here's a link to the file, "stringparsing.bat": http://uploading.com/files/a1m1d2f4/stringparsing.bat/
If you could assist me in getting this program to carry out its task without any errors it would be greatly appreciated!
Here's the "stringparsing.bat" file in full:
#echo off
setlocal enabledelayedexpansion
title BETA
cls
cd C:\script\st
echo.
echo.
echo.
echo Setting Variables...
echo Loading Language Database...
:: ###################################################################################
:: CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE
:: ###################################################################################
TIMEOUT /t 5 /nobreak > nul
goto MAIN
:MAIN
set foo=0
cls
echo.
echo.
echo.
echo.
echo ===================================
echo #################################
echo ####### Main Menu: #######
echo #################################
echo ===================================
echo.
echo.
echo 1.) Create New Language File...
echo.
echo 2.) Load Existing Lanuage File...
echo.
echo 3.) Settings...
echo ---------------------------------------------------------
SET /p CHOICE= Select a Function:
IF %CHOICE%== 1 GOTO CREATE
IF %CHOICE%== 2 GOTO LOAD
IF %CHOICE%== 3 GOTO SETTINGS
GOTO MAIN
:CREATE
cls
title Step 1
echo.
echo.
echo.
echo =================================================================================
echo.
set /p name= please type a name for your new language file:
echo.
echo =================================================================================
cls
echo. > %name%.txt
echo.
echo.
echo.
echo ==============================================================
echo ##############################################################
echo #============================================================#
echo # #
echo # - After you hit enter you will be redirected #
echo # to a Live Typer. so anything you type into #
echo # it will be sent to %name%.txt. #
echo # #
echo # #
echo # - Next, select load language File For Encoding! #
echo # #
echo #============================================================#
echo ##############################################################
echo ==============================================================
set /p line1= :
echo %line1% >> %name%.txt 2> nul
echo %name% > Language_File.txt
attrib +h Language_File.txt
set /a foo+ =1
)
echo.
echo ==========================================================
goto LOAD
:LOAD
set /a foo+ =1
IF %foo%== 2 goto loadexternal
goto LOAD23
:loadexternal
echo.
echo language file is loading now!
set /p name=<Language_File.txt
timeout /t 4 /nobreak > nul
echo.
echo.
echo Language_File Loaded!
pause >nul
goto LOAD23
:LOAD23
cls
echo.
echo.
echo.
echo.
echo.
echo Encoding Your Language File... Please Wait...
echo.
echo.
echo.
for /f "delims=" %%i in (!name!.txt) do (
echo translating "%%i"
set var=%%i
set var=!var:a=1 !
set var=!var:b=2 !
set var=!var:c=3 !
set var=!var:d=4 !
set var=!var:e=5 !
set var=!var:f=6 !
set var=!var:g=7 !
set var=!var:h=8 !
set var=!var:i=9 !
set var=!var:j=10 !
set var=!var:k=11 !
set var=!var:l=12 !
set var=!var:m=13 !
set var=!var:n=14 !
set var=!var:o=15 !
set var=!var:p=16 !
set var=!var:q=17 !
set var=!var:r=18 !
set var=!var:s=19 !
set var=!var:t=20 !
set var=!var:u=21 !
set var=!var:v=22 !
set var=!var:w=23 !
set var=!var:x=24 !
set var=!var:y=25 !
set var=!var:z=26 !
echo !var!
)
echo !var! > !name!.txt
pause >nul
TIMEOUT /t 5 /nobreak > nul
goto MAIN
:END
cls
title SHUTTING DOWN...
echo.
echo.
echo.
echo Terminating service stream...
echo.
echo.
echo.
echo.
echo Done! Thank you for using this program!
TIMEOUT /t 5 /nobreak > nul
::(%xx%) -1 I/O Stream= "SHELL.dll"
:: IF EXIST [&1[Parser_2009]] exit
Exit
:: #####################################################################################
You've got a few problems. First, the access denied problem is from you redirecting to a hidden file.
echo %name% > Language_File.txt
attrib +h Language_File.txt
Note that the first time you run the script, it will work because Language_File.txt won't exist and therefore won't be hidden. The second time you run it, you'll get access denied. I don't know why Windows doesn't let you do that. You can solve this problem in a couple ways.
1. Save your file to the user's temp directory. With this approach your directory won't get cluttered.
echo %name% > %TMP%\Language_File.txt
2. Save your file to a subdirectory that you own so that it doesn't clutter the script's directory.
if not exist workspace mkdir workspace
echo %name% > workspace\Language_File.txt
3. Unhide the file before you use it. Since the file may not exist the first time you run the script, perhaps you should only attrib -h if it exists.
if exist Language_File.txt attrib -h Language_File.txt
echo %name% > %TMP%\Language_File.txt
attrib +h Language_File.txt
4. Don't use Language_File.txt at all! I don't see why you need it. Just use variables to hold the name of the language file. In fact, you already have the name in %name%, right?
Second, you should check the value of your variables to see what they really hold. When you load the contents of Language_File.txt into your variable, it's loading all the contents. That includes the hidden newline characters \r\n, although the script seems to bring them into the variable as spaces. See:
c:\batch\t>echo language file is loading now!
language file is loading now
C:\batch\t>set /p name= <Language_File.txt
C:\batch\t>echo -%name%-
-langfile -
If you echo %name% surrounded by hyphens, you can see that there are 2 spaces after it from (presumably) the newline characters. To solve this problem, you can use set to trim the trailing characters.
C:\batch\t>echo language file is loading now!
language file is loading now
C:\batch\t>set /p name= <Language_File.txt
C:\batch\t>set name=%name:~0,-2%
C:\batch\t>echo -%name%-
-langfile-
In the second example, `%name% doesn't have the hidden characters.
Finally, you only need to use ! to access variables that you set inside the for loop. So all references to !name! should be %name% instead. That's probably your "cannot find file" error.
heres the "stringparsing.bat" file:
#echo off
setlocal enabledelayedexpansion
title BETA
cls
cd C:\script\st
echo.
echo.
echo.
echo Setting Variables...
echo Loading Language Database...
:: ###################################################################################
:: CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE
:: ###################################################################################
TIMEOUT /t 5 /nobreak > nul
goto MAIN
:MAIN
set foo=0
cls
echo.
echo.
echo.
echo.
echo ===================================
echo #################################
echo ####### Main Menu: #######
echo #################################
echo ===================================
echo.
echo.
echo 1.) Create New Language File...
echo.
echo 2.) Load Existing Lanuage File...
echo.
echo 3.) Settings...
echo ---------------------------------------------------------
SET /p CHOICE= Select a Function:
IF %CHOICE%== 1 GOTO CREATE
IF %CHOICE%== 2 GOTO LOAD
IF %CHOICE%== 3 GOTO SETTINGS
GOTO MAIN
:CREATE
cls
title Step 1
echo.
echo.
echo.
echo =================================================================================
echo.
set /p name= please type a name for your new language file:
echo.
echo =================================================================================
cls
echo. > %name%.txt
echo.
echo.
echo.
echo ==============================================================
echo ##############################################################
echo #============================================================#
echo # #
echo # - After you hit enter you will be redirected #
echo # to a Live Typer. so anything you type into #
echo # it will be sent to %name%.txt. #
echo # #
echo # #
echo # - Next, select load language File For Encoding! #
echo # #
echo #============================================================#
echo ##############################################################
echo ==============================================================
set /p line1= :
echo %line1% >> %name%.txt 2> nul
echo %name% > Language_File.txt
attrib +h Language_File.txt
set /a foo+ =1
)
echo.
echo ==========================================================
goto LOAD
:LOAD
set /a foo+ =1
IF %foo%== 2 goto loadexternal
goto LOAD23
:loadexternal
echo.
echo language file is loading now!
set /p name=<Language_File.txt
timeout /t 4 /nobreak > nul
echo.
echo.
echo Language_File Loaded!
pause >nul
goto LOAD23
:LOAD23
cls
echo.
echo.
echo.
echo.
echo.
echo Encoding Your Language File... Please Wait...
echo.
echo.
echo.
for /f "delims=" %%i in (!name!.txt) do (
echo translating "%%i"
set var=%%i
set var=!var:a=1 !
set var=!var:b=2 !
set var=!var:c=3 !
set var=!var:d=4 !
set var=!var:e=5 !
set var=!var:f=6 !
set var=!var:g=7 !
set var=!var:h=8 !
set var=!var:i=9 !
set var=!var:j=10 !
set var=!var:k=11 !
set var=!var:l=12 !
set var=!var:m=13 !
set var=!var:n=14 !
set var=!var:o=15 !
set var=!var:p=16 !
set var=!var:q=17 !
set var=!var:r=18 !
set var=!var:s=19 !
set var=!var:t=20 !
set var=!var:u=21 !
set var=!var:v=22 !
set var=!var:w=23 !
set var=!var:x=24 !
set var=!var:y=25 !
set var=!var:z=26 !
echo !var!
)
echo !var! > !name!.txt
pause >nul
TIMEOUT /t 5 /nobreak > nul
goto MAIN
:END
cls
title SHUTTING DOWN...
echo.
echo.
echo.
echo Terminating service stream...
echo.
echo.
echo.
echo.
echo Done! Thank you for using this program!
TIMEOUT /t 5 /nobreak > nul
::(%xx%) -1 I/O Stream= "SHELL.dll"
:: IF EXIST [&1[Parser_2009]] exit
Exit
:: #####################################################################################
I Finally learned how to format the code snippet.
(heres a link to another copy of it if you need it.)
how to replace a string on the second line in a text file using a batch file?