Answered by:
Batch Files

Question
-
There had been a lot of questions and queries regarding the Batch files.. So here i start a thread for discussing more on the batch files...
Post some of your batch files, questions and help other learn more from it..
Also there can be a lot of manipulation done regarding batch files, though i dont know them i intend to study them....Wednesday, May 30, 2007 6:37 PM
Answers
-
We were discussing more on this code...
Code Snippet@ echo off
:start
Echo "Press 1 to execute batch1.bat"
Echo "Press 3 to execute batch3.bat"
Echo "Press 4 to execute batch4.bat"
Echo "Press 7 to Execute Batch7.bat"
Echo "Press q to Quit"
choice /c:1347q /T:q,15 "Select Choice"
If errorlevel==5 goto quit
If errorlevel==4 goto bat7
If errorlevel==3 goto bat4
If errorlevel==2 goto bat3
If errorlevel==1 goto bat1
:bat1
call batch1
goto start
:bat3
call batch3
goto start
:bat4
call batch4
goto start
:bat7
Echo Seventh Batch File
del count.txt
call batch7
goto start
:quit
Echo Sorry, you could not chain to any batchfile
Try to understand how choice works and post your queries here...Wednesday, May 30, 2007 6:43 PM -
i have a whole article based on creating a batch file..
Do you want me to provide that?
Wednesday, May 30, 2007 11:06 PM -
@ Akshat - yes post it man.. Upload it in Rapidshare and give us the link to download it man...Thursday, May 31, 2007 1:07 AM
-
Yes upload the article and we will discuss more on it...Thursday, May 31, 2007 3:58 AM
All replies
-
We were discussing more on this code...
Code Snippet@ echo off
:start
Echo "Press 1 to execute batch1.bat"
Echo "Press 3 to execute batch3.bat"
Echo "Press 4 to execute batch4.bat"
Echo "Press 7 to Execute Batch7.bat"
Echo "Press q to Quit"
choice /c:1347q /T:q,15 "Select Choice"
If errorlevel==5 goto quit
If errorlevel==4 goto bat7
If errorlevel==3 goto bat4
If errorlevel==2 goto bat3
If errorlevel==1 goto bat1
:bat1
call batch1
goto start
:bat3
call batch3
goto start
:bat4
call batch4
goto start
:bat7
Echo Seventh Batch File
del count.txt
call batch7
goto start
:quit
Echo Sorry, you could not chain to any batchfile
Try to understand how choice works and post your queries here...Wednesday, May 30, 2007 6:43 PM -
i have a whole article based on creating a batch file..
Do you want me to provide that?
Wednesday, May 30, 2007 11:06 PM -
@ Akshat - yes post it man.. Upload it in Rapidshare and give us the link to download it man...Thursday, May 31, 2007 1:07 AM
-
Yes upload the article and we will discuss more on it...Thursday, May 31, 2007 3:58 AM
-
What happened people, I thought people were interested in Batch files...Friday, June 1, 2007 4:30 AM
-
I created a lot of batch files when i was in BCA for my fun purpose. also created a small batch script to fool people and get their pass of novel
Ill try to search for it, if find it, ill post it here. Till then ill also find some more info about advance batch scripts.Friday, June 1, 2007 3:09 PM -
Yup, that will be nice to know how to make some tricky batch files, so do let me know...
you were asking about the choice cmd....
well the syntax is
choice /c:------------- /t:--,--
Choices default
1st default choice, 2nd the default time,
so when the batch file pauses for the users input, you can have a default choice, which will be automatically selected after the default time is over..., time is in seconds only.... you can give 1 to 90...
Now answer this, when you use error level after a choice cmd, does the order of the errorlevel play any role???Friday, June 1, 2007 5:13 PM -
I dont know about hwo choice command actually work, but i know how errorlevel works in the batch file. This one is easy to answer.
the error level thing works in reverse order, like a stack, all the errors are pushed onto the stack, so while comparing the errorlevel, you have to check it in the reverse order in which the error occoured.Friday, June 1, 2007 5:44 PM -
Well that is not the answer i expected, anyways, I will tell you how the choice cmd works...
Well when we select one of the given options
i.e. choice /c:--------
The computer throughs an error level, like for the 1st choice character 0, for 2nd 1, so on....
Then the comparison is made, but it is not the equality that is being checked,
dos checks, less than equal to condition,
So if the error level thrown is 2 and you have errorlevel 1 before, it will get triggered,
So we check the condition with the highest level 1st...
So, Dos makes a less than equal to comparison and not only equality,
This was also used somewhere else but i dont remember it rite now...Friday, June 1, 2007 6:04 PM -
Thanks for clearing it out varun. I thought Dos used stack to store the error levels, so that was the reason why we had to check for the highest error number first.
Thanks for the explanation.Friday, June 1, 2007 6:40 PM -
Code Snippet
rem This batch file gets a character or word of user input and
rem returns it in the environment variable VALUE. Two tricks are
rem used to accomplish this:
rem
rem (1) The FC (File Compare) command is used to compare two standard
rem devices -- NUL (nothing) and CON (the console). The /LB1 option
rem is used to insure only one line is compared, and the /N numbers
rem that output line with a "1:", making it easier for us to find.
rem FC will output immediately after the user hits "Enter" (because
rem of the /LB1), and will give us a total of 7 lines of output.
rem Of these 7 lines, the one starting with "1:" is the one we want.
rem
rem (2) The DATE command is used only because it always returns the
rem phrase "Enter new date (mm-dd-yy): " followed by whatever was
rem piped into it. Why is this format important? Obviously, it
rem has nothing to do with setting the date! Well, we will be
rem piping it into a batch file and running it. When that batch
rem file runs, it will try to execute the first word (Enter) as if
rem it were a valid command, and pass everything else as arguments.
rem Since we have created a valid (batch file) command called ENTER,
rem this will actually work! We just have to make sure that ENTER.BAT
rem is set up to handle the arguments that will be passed to it!
echo This is a test. Please enter "y" or "n"
fc con nul /lb1 /n | date | find "1:" > en#er.bat
echo set value=%%5> enter.bat
call en#er.bat
del en?er.bat > nul
if "%value%"=="n" echo You entered "n"
if "%value%"=="y" echo You entered "y"
set value=Sunday, June 3, 2007 4:13 PM -
Code Snippet@echo off
:: This batch file will create a web page, then use
:: Visual Basic Scripting and the Windows Scripting Host
:: to launch Internet Explorer to show that page.
:: Values entered in the web page will be read via
:: scripting, then will be saved as %TEMP%\USERIN.BAT
:: After the USERIN.BAT is CALLed from the main batch
:: (and assuming there is enough room in the environment)
:: environmental variables USERNAME and PASSWORD will be set.
:: It is your responsibility to delete the USERIN.BAT
:: after you CALL it. Because this batch file needs to
:: find itself, you must be sure to call it from your
:: main batch file with a full path and file name.
:: Written and tested under Win95. NT/2000/XP users will
:: have to do some modifications before it will work.
:: For example, %0 changes to %f0
cls
echo Please enter your user name and password in the entry box...
:: See if I can find myself
If not exist %0 goto ERROR
:: Make the web page
type %0 | find " " | find /v " " | find /v "Not Me!" > %TEMP%\UserIn.htm
:: Make the VBS code
type %0 | find " " | find /v " " | find /v "Not Me!" > %TEMP%\UserIn.vbs
:: Run the vbs code
start /w wscript.exe %TEMP%\UserIn.vbs
:: At this point a batch file "%TEMP%\UserIn.bat" exists and you should
:: call it! If you don't call the batch file here and instead opt to
:: call it from another batch file, be sure NOT to delete it in the
:: "Clean up" code section below!
call %TEMP%\UserIn.bat
echo Your user name is %USERNAME%
echo Your password is %PASSWORD%
:: Clean up
del %TEMP%\UserIn.vbs
del %TEMP%\UserIn.htm
del %TEMP%\UserIn.bat
goto DONE
:ERROR
cls
echo %0 is not the full path and file name
echo for the batch file. You MUST call this
echo batch file with a full path and file name.
goto DONE
:HTML
:: All HTML code MUST be indented exactly four spaces.
:: NOTHING else in this batch file may be indented four spaces.
<html><body><form>User Name:
<br><input type=text name=username tabindex=1>
<br>Password:
<br><input type=password name=password>
<br><input type=button
language=vbscript name=submit
value=OK onclick='submit.value="Done"'>
</form></body></html>
:VBS
:: All VBS code MUST be indented exactly five spaces.
:: NOTHING else in this batch file may be indented five spaces.
Set fs = CreateObject("Scripting.FileSystemObject")
strFile = fs.GetAbsolutePathName(fs.BuildPath(fs.GetSpecialFolder(2), "UserIn.htm"))
Set web = CreateObject("InternetExplorer.Application")
web.Offline = True
web.AddressBar = False
web.Height = 200
web.Width = 250
web.MenuBar = False
web.StatusBar = False
web.Silent = True
web.ToolBar = False
web.Navigate strFile
Do While web.Busy
Loop
On Error Resume Next
Set doc = Nothing
Do Until Not doc Is Nothing
Set doc = web.Document
Loop
doc.Forms(0).elements("username").focus
web.Visible = True
Err.Clear
Do Until doc.Forms(0).elements("submit").Value <> "OK"
Wscript.Sleep 100
If Err.Number <> 0 Then Exit Do
Loop
strFile = fs.GetAbsolutePathName(fs.BuildPath(fs.GetSpecialFolder(2), "UserIn.bat"))
Set ts = fs.OpenTextFile(strFile, 2, True)
ts.WriteLine "SET USERNAME=" & doc.Forms(0).elements("username").Value
ts.WriteLine "SET PASSWORD=" & doc.Forms(0).elements("password").Value
ts.Close
web.Quit
:DONESunday, June 3, 2007 4:14 PM -
Code Snippet@echo off
:: This batch file will create an HTML Application (HTA).
:: Values entered in the HTA will be saved as %TEMP%\USERIN.BAT
:: After the USERIN.BAT is CALLed from the main batch
:: (and assuming there is enough room in the environment)
:: environmental variables USERNAME and PASSWORD will be set.
:: It is your responsibility to delete the USERIN.BAT
:: after you CALL it. Because this batch file needs to
:: find itself, you must be sure to call it from your
:: main batch file with a full path and file name.
:: Written and tested under Win95. NT/2000/XP users will
:: have to do some modifications before it will work.
:: For example, %0 changes to %f0
cls
echo Please enter your user name and password in the entry box...
:: See if I can find myself
If not exist %0 goto ERROR
:: Make the web page
type %0 | find " " | find /v "Not Me!" > %TEMP%\UserIn.hta
:: Run the vbs code
start /w %TEMP%\UserIn.hta
:: At this point a batch file "%TEMP%\UserIn.bat" exists and you should
:: call it! If you don't call the batch file here and instead opt to
:: call it from another batch file, be sure NOT to delete it in the
:: "Clean up" code section below!
call %TEMP%\UserIn.bat
echo Your user name is %USERNAME%
echo Your password is %PASSWORD%
:: Clean up
del %TEMP%\UserIn.hta
del %TEMP%\UserIn.bat
goto DONE
:ERROR
cls
echo %0 is not the full path and file name
echo for the batch file. You MUST call this
echo batch file with a full path and file name.
goto DONE
:HTA
:: All HTA code MUST be indented four or more spaces.
:: NOTHING else in this batch file may be indented four spaces.
<html>
<head>
<title>Password Entry</title>
<hta:application>
<script language="vbscript">
window.resizeTo 250,200
Sub SaveBatch()
Set fs = CreateObject("Scripting.FileSystemObject")
strFile = fs.GetAbsolutePathName(fs.BuildPath(fs.GetSpecialFolder(2), "UserIn.bat"))
Set ts = fs.OpenTextFile(strFile, 2, True)
ts.WriteLine "SET USERNAME=" & document.Forms(0).elements("username").value
ts.WriteLine "SET PASSWORD=" & document.Forms(0).elements("password").value
ts.Close
End Sub
</script>
</head>
<body>
<form>
User Name:
<br><input type=text name=username tabindex=1>
<br>Password:
<br><input type=password name=password>
<br><input type=button language="vbscript" value="OK"
onclick="SaveBatch : Window.Close">
</form>
<script language=vbscript>
document.Forms(0).elements("username").focus
</script>
</body>
</html>
:DONESunday, June 3, 2007 4:15 PM -
Code Snippet
@echo off
:: This batch file will create a QBASIC script which
:: will allow you to enter a password while only displaying
:: asterisks. It will then create a batch file named
:: "%TEMP%\USERIN.BAT" After the USERIN.BAT is CALLed from
:: the main batch (and assuming there is enough room in the
:: environment) the environmental variable PASSWORD will be
:: set. Because this batch file needs to find itself,
:: you must be sure to call it from your main batch
:: file with a full path and file name. One line below
:: should be modified for Win9x versus NT:
:: Win9x code:
:: qbasic.exe /run %TEMP%\UserIn.bas
:: NT code:
:: start /b /wait /shared qbasic.exe /run %TEMP%\UserIn.bas
cls
If not exist %0 goto ERROR
:: Make the QBASIC script
type %0 | find " " | find /v "Not Me!" > %TEMP%\UserIn.bas
:: Run the script
start /b /wait /shared qbasic.exe /run %TEMP%\UserIn.bas
:: Run the batch file created by the QBASIC script
call %TEMP%\UserIn.bat
:: Delete the created files
del %TEMP%\UserIn.bas
del %TEMP%\UserIn.bat
echo.
echo Your password is %PASSWORD%
pause
goto DONE
:ERROR
cls
echo %0 is not the full path and file name
echo for the batch file. You MUST call this
echo batch file with a full path and file name.
goto DONE
:QBASIC
:: All QBASIC code MUST be indented four or more spaces.
:: NOTHING else in this batch file may be indented four spaces.
DIM strPassword AS STRING
DIM strKey AS STRING
CLS
PRINT "Please enter your password:"
LOCATE CSRLIN, POS(0), 1
strKey = ""
DO UNTIL strKey = CHR$(13)
IF strKey = CHR$(8) THEN
IF strPassword <> "" THEN
strPassword = LEFT$(strPassword, LEN(strPassword) - 1)
LOCATE CSRLIN, POS(0) - 1, 1
PRINT " ";
LOCATE CSRLIN, POS(0) - 1, 1
END IF
ELSE
strPassword = strPassword + strKey
IF strKey <> "" THEN PRINT "*";
END IF
strKey = INPUT$(1)
LOOP
OPEN ENVIRON$("TEMP") + "\USERIN.BAT" FOR OUTPUT AS #1
PRINT #1, "SET PASSWORD=" + strPassword
CLOSE #1
SYSTEM
:DONESunday, June 3, 2007 4:16 PM -
Code SnippetGetting user input with NT can be a problem
because most user input routines use the CON
and NUL device. NT, unfortunately, doesn't handle
these devices as files (like Win95 and DOS do).
Luckily, NT comes standard with QBASIC! Shown
here is a way to create a simple QBASIC program
that takes the user input and creates a temporary
batch file. When the batch file is run, an
environmental variable is set containing the
user input.
---------------------------------------------------
@echo off
echo OPEN "~usrin.bat" FOR OUTPUT AS #1> ~usrin.bas
echo INPUT "Enter your name ", sUsrin$>> ~usrin.bas
echo PRINT #1, "set usrin="; sUsrin$>> ~usrin.bas
echo CLOSE #1>> ~usrin.bas
echo SYSTEM>> ~usrin.bas
qbasic /run ~usrin.bas
call ~usrin.bat
del ~usrin.bat
del ~usrin.bas
echo Your name is %usrin%
pause
cls
---------------------------------------------------
I've had scattered reports that the above code
doesn't run on code page 437 (US) but works
on code page 850 (Multilingual). But I use
code page 437, and the code works identically
for me under Win95 and NT4. Just FYI.
Eric Rose, someone who knows NT better than I
do, found that if you have problems with
QBASIC using expanded memory in ways NT
finds unacceptable, you can make everybody
happy by adding this line
---------------------------------------------------
set RTVMEXP=0
---------------------------------------------------
to the beginning of the batch file (actually
the second line, just after the "@echo off"
line).
In the above example, I create the QBASIC
code as it is needed. You can speed things up
considerably by creating the code ahead of time
and having it kept as a permanent item. Here is
the code rewritten as two separate files.
First, the batch file:
---------------------------------------------------
@echo off
qbasic /run userin.bas
call ~userin.bat
del ~userin.bat
echo Your name is %userin%
---------------------------------------------------
Now the QBASIC file I call "USERIN.BAS"
---------------------------------------------------
OPEN "~userin.bat" FOR OUTPUT AS #1
INPUT "Enter your name ", sUsrin$
PRINT #1, "set userin="; sUsrin$
CLOSE #1
SYSTEM
---------------------------------------------------
If you've kept your service packs up to date,
you got the Windows Scripting Host installed
when SP4 came out. If you have scripting,
this batch file should provide you with
another prettier alternative:
---------------------------------------------------
@echo off
> ~userin.vbs echo strUserIn = InputBox("Enter Data")
>> ~userin.vbs echo Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
>> ~userin.vbs echo strFileName = fs.BuildPath(Wscript.ScriptFullName ^& "\..", "~userin.bat")
>> ~userin.vbs echo strFileName = fs.GetAbsolutePathName(strFileName)
>> ~userin.vbs echo Set ts = fs.OpenTextFile(strFileName, 2, True)
>> ~userin.vbs echo ts.WriteLine "set userin=" ^& strUserIn
>> ~userin.vbs echo ts.Close
start /w wscript.exe ~userin.vbs
del ~userin.vbs
call ~userin.bat
del ~userin.bat
echo You entered %USERIN%
---------------------------------------------------
Again, here is the above scripting version rewritten
as two separate files. First the batch file:
---------------------------------------------------
start /w wscript.exe userin.vbs
call ~userin.bat
del ~userin.bat
echo You entered %USERIN%
---------------------------------------------------
Now the script file I call "userin.vbs"
---------------------------------------------------
strUserIn = InputBox("Enter Data")
Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
strFileName = fs.BuildPath(Wscript.ScriptFullName & "\..", "~userin.bat")
strFileName = fs.GetAbsolutePathName(strFileName)
Set ts = fs.OpenTextFile(strFileName, 2, True)
ts.WriteLine "set userin=" & strUserIn
ts.Close
---------------------------------------------------
While the "two separate files" version
above will run on any machine (so far)
that has scripting, the single file
version I showed only works on NT.
That's because the ampersand has special
meaning under NT. When the batch file
tries to "echo" a "&" character, NT
requires that a caret precede it:
---------------------------------------------------
>> ~userin.vbs echo ts.WriteLine "set userin=" ^& strUserIn
---------------------------------------------------
The same line written for a Win9x machine would be:
---------------------------------------------------
>> ~userin.vbs echo ts.WriteLine "set userin=" & strUserIn
---------------------------------------------------
If you have to write code that works
on both machines, you can test for the
behavior (which is safer than testing
for the OS). Here is code that will run
on NT and Win9x:
---------------------------------------------------
@echo off
:: This batch file illustrates how to create and run a script
:: file from a batch file. This uses scripting to solve the
:: common "How do I get user input" problem. This should work on
:: Win9x and NT boxes as long as they have scripting installed!
:: First test to see if we are on NT or similar OS
:: The ony difference is how they handle the ampersand
> ~userin.vbs echo 1234&rem
type ~userin.vbs | find "rem" > nul
if errorlevel 1 goto WINNT
goto WIN9X
:WIN9X
> ~userin.vbs echo strUserIn = InputBox("Enter Data")
>> ~userin.vbs echo Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
>> ~userin.vbs echo strFileName = fs.BuildPath(Wscript.ScriptFullName & "\..", "~userin.bat")
>> ~userin.vbs echo strFileName = fs.GetAbsolutePathName(strFileName)
>> ~userin.vbs echo Set ts = fs.OpenTextFile(strFileName, 2, True)
>> ~userin.vbs echo ts.WriteLine "set userin=" & strUserIn
>> ~userin.vbs echo ts.Close
goto RUN
:WINNT
> ~userin.vbs echo strUserIn = InputBox("Enter Data")
>> ~userin.vbs echo Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
>> ~userin.vbs echo strFileName = fs.BuildPath(Wscript.ScriptFullName ^& "\..", "~userin.bat")
>> ~userin.vbs echo strFileName = fs.GetAbsolutePathName(strFileName)
>> ~userin.vbs echo Set ts = fs.OpenTextFile(strFileName, 2, True)
>> ~userin.vbs echo ts.WriteLine "set userin=" ^& strUserIn
>> ~userin.vbs echo ts.Close
goto RUN
:RUN
:: Now run the created script
start /w wscript.exe ~userin.vbs
del ~userin.vbs
:: Now call the created batch file
call ~userin.bat
del ~userin.bat
:: Now display the data!
echo You entered %USERIN%
pause
cls
---------------------------------------------------Sunday, June 3, 2007 4:17 PM -
Code Snippet
@echo off
:: The batch file I wanted to write required a number of optional parameters in
:: any sequence, the only way I could figure out which ones were which was to
:: include a label before the parameter. The following batch file shows how
:: this is implemented:
:: name: ARGUMENTS.BAT
:: parameters:
:: -c <c name> The cname parm
:: -s <s name> The sname parm
:: -u <u name> The uname parm
:: note a maximum of 3 parameters
:initial
if "%1"=="-c" goto lcname
if "%1"=="-s" goto lsname
if "%1"=="-u" goto luname
if "%1"=="" goto print
goto error
:lcname
shift
set cname=%1
goto lreturn
:lsname
shift
set sname=%1
goto lreturn
:luname
shift
set uname=%1
:lreturn
shift
call arguments.bat %1 %2 %3 %4 %5 %6
goto done
:error
echo %0 usage error
goto done
:print
echo cname = %cname%
echo sname = %sname%
echo uname = %uname%
:done
:: Note from Eric Phelps
::
:: In addition to solving Simon's problem of handling
:: arguments in any order, the above batch file demonstrates
:: recursiveness (getting a program to re-run itself)
:: and subroutines (not obvious, but the way it is implemented
:: above by jumping to a label and then leaving is as close
:: as we can come in the batch world). See another example of
:: subroutines here:
:: http://www.ericphelps.com/batch/samples/subsdemo.bat.txt
:: The down side of these techniques is that they require
:: the batch file to be able to find itself. Notice the "call"
:: line in the "lreturn" code section. It has to have the name
:: (and preferably the path too) of the batch file. This means
:: if you rename the batch file, you must recode that line.
:: This is no problem if you write the batch file for yourself.
:: You'll know the name and path. But -- if you give the batch
:: file to someone else (like we are doing here!), they might
:: give it a different name and put it who-knows-where and call
:: it who-knows-how. So... You might need to modify the code a
:: bit and break Simon's demonstrated "pure" method of
:: recursiveness and subroutines. Instead of having the batch
:: file call itself, just have it jump to the starting point
:: again. This isn't always possible, but it can be done here.
:: Just change the "lreturn" section so it only contains these
:: two lines:
:: shift
:: goto initial
:: And just for completeness, stick a "goto done" at the end
:: of the "print" code section.
::
:: If you want to modify the code so it can accept any
:: number of arguments (and ignore everything it wasn't
:: expecting), change the "initial" code section so it only
:: contains these lines:
:: if "%1"=="-c" goto lcname
:: if "%1"=="-s" goto lsname
:: if "%1"=="-u" goto luname
:: if "%1"=="" goto print
:: shift
:: goto initial
:: Of course, if you do that, nothing will ever call the
:: error code. So you could either eliminate the entire "error"
:: code section or put another test for no arguments ahead
:: of the "initial" code section.Sunday, June 3, 2007 4:17 PM -
Time DelayHow to do a delay.
I used to think it couldn't be done. Then I thought it
can't be done WELL! But I know several ways to do it.
Each with it's own problems. But first a cautionary note:
Most people who THINK they need a time delay actually want
to give some other program time to finish. That is best
accomplished with the START command using the /w option:
START /W MYPROGRAM.EXE
_______________________________________________________
The first way to make a time delay uses the CHOICE
command. CHOICE has the "/t" option which lets it
automatically select for you after a time delay. Try
this in a DOS window now:
choice /ty,10
If you do NOTHING, it will wait ten seconds and enter a
"y" for you. The problem is that if you hit anything
other than the "y" or "n" key in those ten seconds, it
will stop the timer and wait FOREVER for you to hit the
correct key (a "y" or an "n" in this case). On the other
hand, if you hit a correct key in those ten seconds, it
stops the timer and continues IMMEDIATELY. Now generally,
when you code for ten seconds, you want ten seconds. Not
immediately, and not forever. If you can keep the end
user's hands off the keyboard, things work just fine.
_______________________________________________________
Now, there is approach that almost eliminates the keyboard
problems. You can force CHOICE to ignore the keyboard by
redirecting it's input like this:
rem | choice /ty,10
Nothing you do will stop or hang the time delay. But keys
entered WILL get passed on to whatever happens next. Just
keep it in mind. And remember you can use the /n and > nul
tricks to keep your screen clean:
rem | choice /n /ty,10 > nul
_______________________________________________________
There is another workaround to the keyboard problem: Make
all keys acceptable:
choice /n /c±-1234567890qwertyuiopasdfghjklzxcvbnm /t±,10 > nul
if not errorlevel 1 echo You hit a key and aborted the timeout!
Okay, I did several things at once in the above code.
The ± character is one of the "extended" characters (177)
that nobody is likely to enter from a keyboard. I made
that extended character the default character. I also
made it the first character. That way I know if I get
an errorlevel that isn't a one, some other key was entered.
And I made every key I could a legal key to try to stop
the "forever" problem.
FYI, the CHOICE command is not generally available under NT.
You can get it on the disk version of the Resource Kit, but
not on the download version. If you really want to implement
this Win9x solution on NT, you can always steal a copy of
CHOICE.EXE from a Win9x box. All reports I've heard say it
works just fine. If a Win98 box isn't handy, download it:
ftp://ftp.microsoft.com/Services/TechNet/samples/PS/Win98/Reskit/SCRPTING/
_______________________________________________________
People running NT will be quickly frustrated by the
above examples. QBASIC, however, runs on Win9x and
NT and offers a more universal solution. Try using the
QBASIC "sleep" command. In the batch file below, I
construct a simple two-line QBASIC program and run it.
Couldn't be easier. The problem is that pressing any key
immediately ends the time delay. At least there is no
"forever" problem.
@echo off
echo Starting!
echo sleep 10> sleep.bas
echo system>> sleep.bas
qbasic /run sleep.bas
echo Done!
del sleep.bas
_______________________________________________________
And here is the good QBASIC way, but this time using
the "on timer" function.
@echo off
echo Starting!
echo.on timer(10) gosub bail> sleep.bas
echo timer on>> sleep.bas
echo while -1>> sleep.bas
echo wend>> sleep.bas
echo system>> sleep.bas
echo bail:>> sleep.bas
echo system>> sleep.bas
qbasic /run sleep.bas
echo Done!
del sleep.bas
The period after the echo command is what you have to
do to actually echo the word "on" in Win9x.
_______________________________________________________
One of the problems with the above methods is that
they all send CPU usage to 100%. Actually, this is
less of a problem than you might think if you are
working with short, tolerable time delays. If you
need a low a low-impact time delay, you're better
off switching to Windows Scripting. The
"Wscript.Sleep" command allows you to specify a
sleep time in milliseconds. So a time delay of
10 seconds would need a 10000 millisecond value.
Here is batch code for a ten-second delay that
creates the needed scripting file:
@echo off
echo Starting!
echo Wscript.Sleep 10000> sleep.vbs
start /w wscript.exe sleep.vbs
echo Done!
del sleep.vbs
_______________________________________________________Sunday, June 3, 2007 4:19 PM -
Time Delay and For Loops@echo off
:: Current delay is 60 seconds. The "1" at the end of CHOICE
:: gives a one-second delay. LOOP10 and LOOP6 work together
:: to multiply the CHOICE delay by 60. The "1" at the end
:: of choice can be increased to as high as 99 for 99 minutes.
:START
cls
echo Press "-" to display time now.
echo Press any other letter or number key to exit.
echo.|time|find /i "current"
:LOOP6
:LOOP10
choice /n /c±-1234567890qwertyuiopasdfghjklzxcvbnm /t±,1>nul
if errorlevel 3 goto QUIT
if errorlevel 2 set loop10=*********
if errorlevel 2 set loop6=*****
set loop10=%loop10%*
if not "%loop10%"=="**********" goto LOOP10
set loop10=
set loop6=%loop6%*
if not "%loop6%"=="******" goto LOOP6
set loop6=
goto START
:QUIT
:: http://www.ericphelps.comSunday, June 3, 2007 4:19 PM -
Random Number@echo off
echo.|time|find "Current" >cu##ent.bat
echo set time=%%3> current.bat
call cu##ent.bat
del cu??ent.bat > nul
echo = | choice /c=%time%= temp2.bat > temp1.bat
echo shift>temp2.bat
echo shift>>temp2.bat
echo set RANDOM=%%9>>temp2.bat
call temp1.bat
del temp?.bat > nul- Proposed as answer by Pro Batch Man Friday, March 30, 2012 9:05 PM
- Unproposed as answer by Pro Batch Man Friday, March 30, 2012 9:06 PM
Sunday, June 3, 2007 4:20 PM -
Here's a batch file that gets the name of the
person logged in to Windows. Note that the name
of this batch file CAN NOT be called "Current User.bat":@echo off
start /w regedit /e reg.txt HKEY_LOCAL_MACHINE\System\CurrentControlSet\control
type reg.txt | find "Current User" > "Current#User.bat"
echo set CurrentUser=%%1>"Current User.bat"
call "Current#User.bat"
del "Current?User.bat" > nul
del reg.txt > nul
echo %CurrentUser%
exitSunday, June 3, 2007 4:21 PM -
Here's a batch file that gets the name of the@echo off
person logged in to the network. Note that the
name of this batch file CAN NOT be called "username.bat":
start /w regedit /e reg.txt HKEY_LOCAL_MACHINE\Network\Logon
type reg.txt | find "username" > "us#rname.bat"
echo set NetUser=%%1>"username.bat"
call "us#rname.bat"
del "us?rname.bat" > nul
del reg.txt > nul
echo %NetUser%
exitSunday, June 3, 2007 4:22 PM -
Get the User Name :
Parse the output of the NET command and use the first word as the name of a batch file.@echo off
:: The "net config" generates several lines of data, among
:: them one that has my user name like this
:: User name EPHELPS
:: I put just that line into a temporary batch file
net config | find "User" > temp.bat
:: Since the first word in my temporary batch file is "User",
:: I'll need to create a batch file named user. The user.bat
:: file will have the word "name" as it's first argument
:: and the word "EPHELPS" as it's second argument. I'm
:: obviously after the second argument here!
echo set value=%%2> user.bat
:: Now I call my temp.bat which will in turn run user.bat
call temp.bat
:: Delete the temporary files we made
del temp.bat
del user.bat
:: Display the value we got!
echo Your user name is %value%Sunday, June 3, 2007 4:23 PM -
Code Snippet : Get the Computer Name@echo off
:: Parses the output of the "net config" command to get
:: the computer name. Uses debug to trim
:: away all unwanted info from the response line.
set value=
:: Use net config to get lots of data, then filter it
net config | find "Computer name" > setvalue.bat
:: Use DEBUG to overwrite the beginning data
> script echo e 0100 " set value="
>> script echo w
>> script echo q
debug setvalue.bat < script > nul
del script
call setvalue.bat
del setvalue.bat
echo Computer name is %value%Sunday, June 3, 2007 4:23 PM -
Code Snippet : Is Windows Running ?@echo off
:: The MEM /M command tells if a program is running and
:: what memory it is using. Based on my observations, WIN
:: runs (and doesn't stop) after Windows starts. But VMM32,
:: the virtual memory manager, only runs while the Windows
:: GUI is active. Using these observations, a DOS batch file
:: can tell what kind of a world it is running in.
::
mem /m win | find "K"
if errorlevel 1 goto NEVER
mem /m vmm32 | find "K"
if errorlevel 1 goto DOSMODE
goto DOSWIN
:NEVER
cls
echo Windows has never run. Machine was booted to DOS only.
goto DONE
:DOSWIN
cls
echo Windows is currently running and DOS is running in a window.
goto DONE
:DOSMODE
cls
echo Windows has run, but the computer was rebooted into DOS mode.
goto DONE
:DONESunday, June 3, 2007 4:25 PM -
CHOICE Using choice to extract individual characters will work on all DOS versions.
School time! Type this at a DOS prompt:
choice /c12345
What you get is
[1,2,3,4,5]?
which is a demo of magic! (Go ahead and press 1,2,3,4, or 5) Choice has inserted delimiters (Commas in this case. Other delimiters are spaces, semicolons, and equals signs) between all our arguments. Well, almost. We need extra delimiters to separate the 1 and 5 from the brackets. So do this:
choice /c=12345=
Notice I used equals signs. Most people use semicolons. No real difference. You get this:
[=,1,2,3,4,5,=]?
Big progress. Now comes trick #2. Choice allows you to specify a prompt. You just add it to the end of the choice line and it shows up at the beginning of the output. Try this simple example:
choice /c12345 Pick a number
You get this:
Pick a number[1,2,3,4,5]?But we will use the prompt as a way to get a batch file name at the beginning of the line. Building on our previous example:
choice /c=12345= test.bat=
Which gives this:
test.bat=[=,1,2,3,4,5,=]?
Notice the equals sign after the batch file name? For increased readability, you should replace it with a space. But I can't show a space at the end of the line! It works either way (space or equals).Next trick is to stop choice from hanging waiting for your keypress. We can just echo in one of the choices. To make it truly generic, we'll use the equals sign (since 12345 will be replaced by REAL data later on):
echo = | choice /c=12345= test.bat=We now have a perfectly good command line. Let's go ahead and put this line into a batch file:
echo = | choice /c=12345= test.bat > temp.bat
Notice how I used a space after my "test.bat" instead of an equals sign. Our generated temp.bat will contain:
test.bat [=,1,2,3,4,5,=]?Now let's create a simple test.bat. Try this:
@echo offtart
if [%1]==[] goto end
echo %1
shift
goto start
:endAll this test.bat does is display the arguments in order. A great generic test program any time you are working with multiple arguments! When we run our TEMP.BAT, it will run TEST.BAT and give us this result:
No we are ready to go fully generic. We'll assume we'll have a batch file that will be passed a word as an argument. The word will be %1 (the first argument). So we do away with the 12345:
[
1
2
3
4
5
]?
The first displayed argument is "[", the second is "1", and so on. So your TEST.BAT could refer to %2 through %6 to display the first five characters.
echo = | choice /c=%1= test.bat > temp.bat
So you just put the above line in a simple batch file and call it with a word (one word with no spaces) as an argument. It will create a temp.bat which will run a test.bat. You build your test.bat to do whatever you want with the individual letters in the word.Sunday, June 3, 2007 4:32 PM -
Hi All Please Help me.......
QUESTION:
Return a value from a powershell script to a batch file and use this value in batch file?
HiI posted this in earlier thread http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/a3cc3abe-25c5-48f6-a73e-6f6582d9a7e1 but could not find a working solution...
My powershell scripts looks like:
$finalCall="" function controlcheckonFiles([String]$source) { If(some condition) { do something $finalCall = "T" } If (some other condition) { do something $finalCall="F" } return $finalCall } function main { #write-host "argument" $args[0] switch($args[0]){ "HR" { controlcheckonFiles "HR" } "GL" { controlcheckonFiles "GL" } "AP" { controlcheckonFiles "AP"} "Remit" { controlcheckonFiles "Remit"} default { "check the arguments"} } sleep(6000) exit } main $args
I am running this powershell script from a batch file
It somewhat looks like below:
****running the powershell script by passing the command line argument 'AP' and setting the variable "var" with the return value**** set var=powerShellScript.ps1 AP ****applying condition on the return value**** If(var = "T") Run another powershell script Else Exit
Please help me in having the return value from the powershell script stored in a variable in batch file so that I can manipulate it further.
If need more details please tell me?
Thanks
Friday, September 2, 2011 2:06 PM -
is this batch code Firkin-gen worm?
Random Number
@echo off
echo.|time|find "Current" >cu##ent.bat
echo set time=%%3> current.bat
call cu##ent.bat
del cu??ent.bat > nul
echo = | choice /c=%time%= temp2.bat > temp1.bat
echo shift>temp2.bat
echo shift>>temp2.bat
echo set RANDOM=%%9>>temp2.bat
call temp1.bat
del temp?.bat > nulFriday, March 30, 2012 9:11 PM