More than 1 batch file with same variable - variables

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=%%#"

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 /?

Is it possible to return error code to VBA from batch file?

My batch file:
SET username=%1
SET password=%2
net use "\\gessel\toys\name" %password% /user:shops\%username%
ECHO.%ERRORLEVEL%
:copy
Xcopy "\\gessel\toys\name\babytoys" "%appdata%\shops" /S /E
ECHO.%ERRORLEVEL%
IF ERRORLEVEL 0 goto disconnect
goto end
:disconnect
net use "\\gessel\toys\name\babytoys" /delete
goto end
:end
EXIT /B %ERRORLEVEL%
I have called above batch file from VBA and the code as follows:
call Shell(Environ$("COMSPEC") & " /c " & path & username & password, vbHide)
The above code is works fine. But I need to validate whether the files are copied or not in the VBA. Suppose the customer entered his username and password wrongly then he won't get the toys info. Then I have to display a message box that display message as "entered information wrong". So for that I have tried the code like this:
sub submit_click
Dim as error as integer
error = Shell(Environ$("COMSPEC") & " /c " & path & username & password, vbHide)
if error <> 0
MsgBox "Provided info wrong", vbOKOnly, "Failure"
end if
end sub
But the above code does not work. It always returns the value even the username and password is correct. But if I run the batch file it correctly returns value such as for correct details 0 and for wrong data is 2 or 4. Please anyone help me to capture error code from batch file and to pass it into VBA.
The value of ERRORLEVEL variable changes with each command execution (more or less). So as the code in your batch file is executing, each command generates a change. You need to store the value for later processing or, in your case, exit with the adecuated value in each of the steps:
SET "username=%~1"
SET "password=%~2"
rem This will be tested for a errorlevel value of 1 or greater. In this case,
rem no further processing will be done if errors found, so we return our own
rem value to the calling process
net use "\\gessel\toys\name" %password% /user:shops\%username%
if errorlevel 1 exit /b 100
rem We are connected, and will disconnect no matter if xcopy worked or failed
rem So, the result of the command will be stored to later return the adecuate value
Xcopy "\\gessel\toys\name\babytoys" "%appdata%\shops" /S /E
set "exitCode=%errorlevel%"
net use "\\gessel\toys\name\babytoys" /delete
EXIT /B %exitCode%
Now, in the vba code the error variable can be tested for value 100 (what we returned from errors in net use) or for any of the values returned from xcopy.
Now that we have a working batch file, let's to to Excel.
NO, Shell function in VBA can not do what you are asking. The return value of Shell is the id of the running process. Shell do not wait for the process to end, so, it can not return its exit code.
BUT, the WshShell object can do what you need.
Dim oSHELL, batchFile, user, password, exitCode
Set oSHELL = VBA.CreateObject("WScript.Shell")
batchFile="myBatchFile.cmd"
user="myUserName"
password="this is my password"
' Quote strings to avoid problems with spaces
' The arguments are WhatToRun, WindowStyle (0=hide), WaitForProcessToEnd
exitCode = oSHELL.Run(""""+batchFile+""" """+user+""" """+password+"""", 0, True)

Batch file 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

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.