Batch file variables - variables

So I have this batch file to backup some programs and also restore them if needed. I have it automated to create folders with the current date each time these programs are backed up. So far I have it set so you can enter a variable as one of the current folder dates that are backed up and when entered correctly it will display "CMS restore completed ! ! !" however, if nothing is entered or the wrong date is entered it will still display "CMS restore completed ! ! !"
I would to be able to use the dates in a txt file to validate this variable so only the dates shown in the txt file will allow the rest of the batch file to run. I would like it to be able to tell me that an invalid date not shown in the txt file will not allow the batch file to keep running.
Any help would be greatly appreciated.
Thanks
BATCH FILE BELOW
$:CMS
#ECHO OFF
cd\1\mybackup\
CLS
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET /p VARIABLE=
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored ! ! !
PAUSE
GOTO 2
VARIABLES FROM TEXT FILE BELOW
2013-08-05
2013-08-06
2013-08-07
New Folder
New Folder (2)
New Folder (3)
New Folder (4)
New Folder (5)

#ECHO OFF
cd\1\mybackup\
CLS
:again
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt | find "-"
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET "VARIABLE="
SET /p VARIABLE=
if not defined variable echo Nothing entered?&goto again
type list.txt|findstr /i /b /e "%variable%" >nul
if errorlevel 1 echo Invalid date entered&goto again
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored to %variable% ! ! !
...
Notes:
added label :again to repeat question
piped LIST.TXT through FIND to show only lines containing "-" (ie. dates)
Set variable to NOTHING as SET/P with just enter will leave the variable
UNCHANGED, not clear it.
Detect nothing-entered; respond and prompt again
match any line from list.txt to string entered - full match /b begins /e and ends /i but case-insensitive.
Could pipe through FIND again to match against date-type line if required.
If entered data not found in file, report and prompt again
Added restore-entry to CMS Restored message.

Try something like this to catch no date entered. I edited to add code to catch invalid date (untested). Of course it will fail in the year 2100 and you need to decide if you need to be more discretionary. Corrected!
#ECHO OFF
cd\1\mybackup\
:Retry
CLS
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET /p VARIABLE=
IF "%VARIABLE%"=="" ECHO.Please enter a date & PAUSE & GOTO :Retry
FOR /D %%A if (20??-*) DO IF EXIST "%%A" GOTO :DoCopy
ECHO.Please enter a valid date & PAUSE & GOTO :Retry
:DoCopy
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored ! ! !
PAUSE
GOTO 2

Related

Tricky variable setting from a text file

I have a windows batch file that reads in various lines of a text file for processing. During the execution I have to open another text file that has only one line in it. The line contains a serial number with about 3 or 4 spaces after the end.
I need to read in this file called (value.txt), grab the data in the first line and assign the value to a variable without any spaces at the end.
After that I need to add the .pdf extension to this variable and set to another variable.
I then need to then check if the variable with the pdf extension exists in the current directory as a file name. If it does then can I change the variable value to add -1 before the .pdf. If this file still exists then try -2 etc.
Thus
File name read in called value.txt
55400TERM1 (variable VAR1 is assigned with no spaces)
55400TERM1.pdf (variable VAR2 is set with the .pdf extension)
55400TERM1-1.pdf (variable VAR2 is updated if 55400TERM.pdf exists)
55400TERM1-2.pdf (variable VAR2 is updated if 55400TERM1.pdf exists)
Etc etc - loops until it cannot file a existing file with the variable value.
Here is a comment batch script for this task:
#echo off
rem If text file with file name does not exist in current
rem directory, exit this batch file as nothing can be done.
if not exist value.txt (
echo %~f0: Missing file "value.txt" in "%CD%".
goto :EOF
)
rem Read first line from text file. Command FOR automatically splits up the
rem line into strings using space and horizontal tab character as string
rem delimiter. As the line contains just one string with trailing spaces
rem most likely caused by wrong redirecting an output into the text file
rem the single string is assigned to the variable with no trailing spaces.
for /F %%I in (value.txt) do (
set "FileName=%%I"
goto CheckFile
)
echo %~f0: No string in file "value.txt" in "%CD%".
goto :EOF
:CheckFile
if exist "%FileName%.pdf" goto FindLatestFile
echo No file "%FileName%.pdf" found in "%CD%".
set "FileName=%FileName%.pdf"
goto ProcessFile
rem The command DIR as used here lists all files matching the wildcard
rem specification in reverse order according to last modification date.
rem This batch file assumes that the file with highest number is the
rem newest modified file. This speeds up determining the file with the
rem highest number in file name. For an alphabetical reverse order it
rem would be necessary that all files have the same number of digits,
rem i.e. the files are *-01.pdf, *-02.pdf, ..., *-10.pdf, *-11.pdf as
rem otherwise the alphabetical order would be *-1.pdf, *-10.pdf, *-11.pdf,
rem *-2.pdf, ..., *-9.pdf and then last file would be determined wrong.
:FindLatestFile
for /F %%I in ('dir /O-D /TW /B "%FileName%-*.pdf" 2^>nul') do (
set "LastFileName=%%~nI"
goto FoundLatestFile
)
echo No file "%FileName%-*.pdf" found in "%CD%".
set "FileName=%FileName%-1.pdf"
goto ProcessFile
:FoundLatestFile
for /F "tokens=2 delims=-" %%I in ("%LastFileName%") do set "LastFileNumber=%%I"
set /A LastFileNumber+=1
set "FileName=%FileName%-%LastFileNumber%.pdf"
:ProcessFile
echo Next file is: %FileName%
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
dir /?
for /?
goto /?
if /?
rem /?
set /?

More than 1 batch file with same variable

I was wondering if it was even possable to have the same variable in 2 different batch programs.
:home
Set /p Name=What is your Name?
Set /p Com=What Command do you wish to use?
If %Com% == #HELP goto msgbox
(MORE IF's ARE USED)
goto msgbox
:msgbox
cls
start msgbox.cmd
Echo Welcome to the MSGBOX PROGRAM %Name%
%Com% Code was typed, here is the Help file
goto Help
:Help
cls
(display's the help for program)
Set /p return=Would you like to return?
If %return%==Y goto home
If %return%==N goto exit
(Set errorlevel==1 if no selection)
:exit
cls
Echo press Enter to exit program
pause >nul
yes.
1) If you call the second bat file from the first , the second will inherit all variables.
2) You can also define environment variable.You can use SETX command
setx variable value
Though it's written in the registry you cannot use it straightforward - it will be accessible in the next cmd sessions.So you'll need temporary variable in the script:
Set /p Com=What Command do you wish to use?
rem making variable accessible for the next run or for another batch
setx Com %com%
And you can override its value for every cmd session or script you want with set.After that it will use the registry value again.
3) And you can also use a temp file, but this will require to read it in the next batch :
Set /p Com=What Command do you wish to use?
echo %com%>c:\command.file
in the next script you'll need to use:
for /f "useback tokens=* delims=" %%# in ("c:\command.file") do set "com=%%#"

Convert text file to Word docx

I need VBA code that will convert a text file (.txt) to a MS Word document (.docx). Does anyone have code to accomplish this? I have many text files within a directory and would like to batch convert them to docx files within the same directory or a VBA created directory using the same directory name with "converted" added to the directory name. I have upwards of 800 txt files to be converted.
Thank you,
Nelson
You can create a VBA script / macro in Excel by recording the steps to import the text file and save it to an Excel (xls, xlsx) file. I have done this with Excel, but Word has similar recording / macro functionality.
Here I've created a script that does exactly the opposite.Here's a reworked one that creates a docx from txt (it is a vbscript/batch hybrid and needs to be saves as a .bat) NEED ADMIN PERMISSIONS (to start invisible word mainly) :
'>nul 2>&1|| #copy /Y "%windir%\System32\doskey.exe" "'.exe" >nul
'&&#echo off && cls &&goto :end_vbs
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = FALSE
'Open txt for reading
Set WordDoc = WordApp.Documents.Open(WScript.Arguments.Item(0),false)
'wdFormatText 2
'wdFormatUnicodeText 7
'wdFormatDocumentDefault 16
'http://msdn.microsoft.com/en-us/library/office/ff839952.aspx
WordDoc.SaveAs WScript.Arguments.Item(1) ,16
WordDoc.Close()
WScript.Quit
:end_vbs
'& if "%~1" equ "-help" echo %~n0 text_document [ destination ]
'& if "%~1" equ "" echo txt document not given & exit /b 1
'& if not exist "%~f1" echo txt document does not exist & exit /b 2
'& if "%~2" equ "" ( set "save_as=%~dpn1.docx") else ( set "save_as=%~2")
'& if exist "%~f2" del /s /q "%~f2"
'& for %%# in ("%save_as%") do set "save_as=%%~dpn#"
'& taskkill /im winword* /f >nul 2>&1
'& cscript /nologo /E:vbscript %~f0 "%~f1" "%save_as%"
'& pause
'& rem del /q '.exe
May be I should create a jscript/bat hybrid as the code will be more convenient...
Anyway this accepts 2 arguments one for the .txt file and one for the .docx desination but the txt file will stay undeleted. You can use this to iterate your txt files convert and delete them

Batch script to keep asking for username until correct user name is entered

I am not good with writing batch scripts, but here is what I am trying to achieve. I want to execute some sql (oracle) scripts from command prompt, but script cannot be run by one particular user name. So, whenever I want to run a script as that particular user name, I should see a message "Cannot Login As USER" and prompted to re-enter the user name. And this should continue till any other username is entered. I have the below script so far. Please help. Please ignore my poor batch scripting skills. :)
#ECHO OFF
Echo.
SET /P uname=Username:
IF %uname% == "notallowed" GOTO :LOGIN_ERROR GOTO :LOGIN
:LOGIN_ERROR
ECHO Username Cannot Be notallowed
SET /P uname=Username:
IF %uname% == "notallowed" GOTO :LOGIN_ERROR GOTO :LOGIN
:LOGIN
echo.
SET /P pass=Password:
echo.
SET /P mydatabase=Database:
echo.
rem set oracle_sid=ins
sqlplus -s %uname%/%pass%#%mydatabase%
#C:/My_Folder/test.sql \n
sqlplus exit
Thanks a bunch!
Try this...
#ECHO OFF
:GET_USER
ECHO.
SET /P uname=Username:
IF %uname%==notallowed (
ECHO Username Cannot Be notallowed
GOTO GET_USER
)
REM The rest of the script...
Use an If statement and add goto "marker." example.
:login
set /p username=
If %username% == "CorrectUsername" goto next
GOTO login
:next
'Rest of your code goes below.

How to copy value in clipboard to a variable?

I have a string in clip, and I want to copy it to a variable var.
I have to use that string to find further sub-strings in variable.
You can take advantage of the functionality built into internet explorer, and use its clipboard object. Then you can wrap up the VBScript which accesses the IE objects with a command script:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :GetClipboardText Text
ECHO %LineCount% lines copied.
ECHO Line1: %Text1%
ECHO Line2: %Text2%
ECHO Line3: %Text3%
ECHO Line4: %Text4%
ENDLOCAL
GOTO :EOF
:GetClipboardText
CALL :GetTempFilename TempFile
ECHO Set objHTML = CreateObject("htmlfile")>%TempFile%
ECHO WScript.Echo objHTML.ParentWindow.ClipboardData.GetData("text")>>%TempFile%
SET LineIndex=1
FOR /F "delims=" %%A IN ('%TempFile% //NOLOGO') DO (
SET %1!LineIndex!=%%A
SET /A LineIndex=!LineIndex!+1
)
SET LineCount=%LineIndex%
DEL %TempFile%
GOTO :EOF
:GetTempFilename
FOR /F "delims=:. tokens=2-5" %%A IN ('ECHO ^| TIME') DO SET T=%%A%%B%%C%%D & GOTO :X
:X
CALL :Trim %T% T
SET %1=%Temp%\TMP%T%.vbs
GOTO :EOF
:Trim
SET %2=%1
GOTO :EOF
Unfortunately, due to the nature of the command script engine, I have to split up the text into lines. In my example, %LineCount% will contain the number of lines, which will be retried by %Text1%, %Text2%, and so on.
Using The clip command
but it don't exist in Windows XP :(
It depends upon your operating system, toolkit, language. If you code in C++ with Qt on Linux, you could use QClipboard::text
Batch files can't directly interact with the clipboard. However, there are various people that have written little tools to do this for you, so you could get the GetClip tool from this website.