Windows batch choice command for Windows XP & 2003 - windows

Is there a way to prompt users for input (ie: Yes/No) from a Windows batch script that works on XP and Windows 2003 server? It seems some commands (ie: choice) only work on one OS and not others.

Use the SET command with the /P switch.

SET /P RESULT=Y or N?
ECHO %RESULT%

Note that the SET /P command does not support all the same features as the CHOICE command. Namely:
It doesn't restrict the user to entering a valid value
The user has to press enter
You have to check for casing differences (e.g. "A" vs "a")
There is no way to default to a certain choice after a certain amount of time
For these reasons, I still prefer to use the CHOICE command rather than the SET /P command. To do this, you just need to include CHOICE.COM along with your batch file. You can download CHOICE.COM from Microsoft via the MS-DOS 6.22 Supplemental Disk. Here's the link:
http://support.microsoft.com/kb/117600

This will basically mimic what choice does, you will need to put it as a subroutine in your batch file. I also prefer choice but I need something portable that will run on Windows XP.
You can then modify this to accept other "choices," however this will work as case insensitive and repeat the prompt until the user explicitly enters Y, y, N, or n.
:yesorno
set /p choice=%2
if /i NOT %choice% == n (
if /i NOT %choice% == y goto yesorno
)
set "%~1=%choice%"
goto :eof
You would then call this subroutine via:
call :yesorno answer "Do you want to continue? [Y/n]: "
It's been working very well for me so far.

For instance you could use this:
SET /P ANSWER=y OR n?
If "%answer%"=="y" goto yes
If "%answer%"=="n" goto no
Enjoy!

Windows Millenium's CHOICE.COM works fine for me under XP SP3.
However, mine is hungarian language, but you can probably find its original english variant, for example searching for "windows millenium ebd".
http://s000.tinyupload.com/index.php?file_id=57468192666746678653

Related

TIMEOUT.EXE alternative for legacy Windows OSes?

I am trying to write a batch script that is as universal across Windows versions as possible (or at least from XP to 10). Everything is compatible so far (just some echoes and variable setting), except it uses the TIMEOUT.EXE command, which isn't available in XP or below.
I tried copying the exe over to no success. I was wondering if, through some clever coding, if this is possible. I basically need it to wait X amount of seconds before continuing, or allow a keypress to continue.
I tried using sleep.exe from the server 2003 utilities pack while piping it to set /p "=" and vice versa, but that didn't work either.
Any help is appreciated.
There is the choice command command that offers a default option together with a timeout.
For instance:
rem /* Wait for 10 seconds and take the default choice of `0`;
rem you can interrupt waiting with any of the keys `0` to `9` and `A` to `Z`;
rem you cannot use punctuation characters or white-spaces as choices: */
choice /C 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ /D 0 /T 10
rem // The `ErrorLevel` value is going to be set to a non-zero value.
Not the greatest of tools, but using choice with a custom message and a timeout of (5 seconds in this demo), with keystroke interrupt (any key, besides Enter esc etc.)
#echo off
choice /c qwertyuiopasdfghjklzxcvbnm1234567890 /cs /n /M "Timeout is 5 seconds.. press any key to Continue." /D c /T 5
echo 1 > null
there are a lot of ways. PING seems to be the most popular. You can try also
with w32tm
w32tm /stripchart /computer:localhost /period:5 /dataonly /samples:2 1>nul
or wtih typeperf:
typeperf "\System\Processor Queue Length" -si 5 -sc 1 >nul
with mshta:
start "" /w /b /min mshta "javascript:setTimeout(function(){close();},5000);"

Windows CMD Start and wait for the default application in a batch file

I am trying to start the default application for a file, wait for it to complete, and then continue with my batch file. The problem is that start, when used below simply creates another command prompt window with the example.doc in the title bar. I can use call instead of start, but then call does not wait for the program to finish before going to the next line. It appears that start needs to have an executable name and will not work with the default application system in windows.
Any ideas how I can make this happen without having to hardcode the windows application in the batch file as well?
set filename=example.doc
start /wait %filename%
copy %filename% %filename%.bak
How do I start the default application for a file, wait for completion, then continue?
It appears that start needs to have an executable name and will not work with the default application system in windows.
start, when used below simply creates another command prompt window with the example.doc in the title bar
start /wait %filename%
The above command won't work because %filename% is used as the window title instead of a command to run.
Always include a TITLE this can be a simple string like "My Script" or just a pair of empty quotes ""
According to the Microsoft documentation, the title is optional, but depending on the other options chosen you can have problems if it is omitted.
Source start
Try the following command instead:
start "" /wait %filename%
Alternative solution using the default open command
Any ideas how I can make this happen without having to hardcode the
windows application in the batch file as well?
One way is to use assoc and ftype to get the default open command used for the file then execute that command.
The following batch file does that for you (so no hard coding of windows applications is needed).
Open.cmd:
#echo off
setlocal enabledelayedexpansion
set _file=example.doc
rem get the extension
for %%a in (%_file%) do (
set _ext=%%~xa
)
rem get the filetype associated with the extension
for /f "usebackq tokens=2 delims==" %%b in (`assoc %_ext%`) do (
set _assoc=%%b
)
rem get the open command used for files of type filetype
for /f "usebackq tokens=2 delims==" %%c in (`ftype %_assoc%`) do (
set _command=%%c
rem replace %1 in the open command with the filename
set _command=!_command:%%1=%_file%!
)
rem run the command and wait for it to finish.
start "" /wait %_command%
copy %_file% %_file%.bak 1>nul
endlocal
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
assoc - Display or change the association between a file extension and a fileType
enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
for - Conditionally perform a command several times.
for /f - Loop command against the results of another command.
ftype - Display or change the link between a FileType and an executable program.
start - Start a program, command or batch script (opens in a new window).
variable edit/replace - Edit and replace the characters assigned to a string variable.
Simply use the filename directly as command, unless that filename is a batch file, in which case use call.
In a batch file invocation of a GUI subsystem executable is blocking, unlike for an interactive command.
Use the start command when you don't want blocking execution.
There is a subtle point about “default application”, namely that a file type can have a registered default application for the graphical shell, e.g. its “Open with…”, without having an assoc/ftype association, or different from that association.
I'm not entirely sure of which registry entries are used for this. I've always had to look it up and research it each time. As I recall it's not well-documented.
But hopefully you're OK with just the assoc/ftype scheme.
A further subtle point about “default application”: on the laptop I'm writing this on the ftype association for text files is to open them in Notepad:
[H:\forums\so]
> assoc .txt
.txt=txtfile
[H:\forums\so]
> ftype txtfile
txtfile=%SystemRoot%\system32\NOTEPAD.EXE %1
[H:\forums\so]
> _
And this is what the graphical shell (Windows Explorer) will do.
But cmd.exe looks inside files, and if it finds an executable signature then it tries to run the text file as an executable, even in Windows 10:
[H:\forums\so]
> echo MZ bah! >oops.txt
[H:\forums\so]
> oops.txt
This version of H:\forums\so\oops.txt is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
[H:\forums\so]
> _

How to start a system "beep", from the built-in pc speaker, using a batch file?

I have written a batch script in an interactive mode, for making some tasks.
Sometimes, These tasks takes a long time to be finished, and then the batch asks if the user wants to go on to the next task, or back to the Batch's Main Menu or... etc
Now, what I want to do, is to add an "Interactive Alarm" command, that sounds a small short beep (Ex: Like the one when we turn on our PCs), to alert the batch user for new questions .
I don't know if this is possible or not, but the most important thing for me, NOT to use a GUI application like WMP or so..
I just want to do this from the Background, even If that beep has to be made from the free speaker, or by using a Third-Party CLI Application (Btw, I've Cygwin installed on my Win7-x64) .
Please note that, I will add that alarm command exactly before the interactive questions, waiting for user's answer to get to the next stage, so I can't just finish the batch, by making a real error beep !
So, would somebody please tell me how to do this ?
Appreciate your help :)
WARNING: rundll32.exe Kernel32.dll,Beep 750,300 no longer works well from the command line on modern windows systems as rundll32 no longer accepts integer values (again, through the command line) and this will play the beep with the default values which is too long (and frequency is irritating):
REM Again, with warnings about running this from the command line...
rundll32.exe Kernel32.dll,Beep 750,300
or
rundll32.exe cmdext.dll,MessageBeepStub
or
rundll32 user32.dll,MessageBeep
With rundll functions you won't need special symbols like ^G. With the first method you can also set the frequency and the time you want to beep, though see the warning that those parameters no longer work on modern systems from the command line and will instead play the annoying defaults.
UPDATE
other options are:
powershell "[console]::beep(500,300)"
or using systemSounds.bat
call systemsounds.bat beep
The capability of beeping depends on the mainboard and if the mainboard has a system speaker - which has increasingly become a rarity as systems tend to depend solely on "normal" speakers instead. An alternative is to play sound through those speakers. Here are some options:
Using the speaking capabilities of the SAPI.SpVoice:
mshta "javascript:code(close((V=(v=new ActiveXObject('SAPI.SpVoice')).GetVoices()).count&&v.Speak('beep')))"
Here this is wrapped in a batch file and the words can be passed as an argument.
SAPI.SpVoice can be used for playing wav files and you have some packaged with the default Windows installation. You can use this script:
spplayer.bat "C:\Windows\Media\Windows Navigation Start.wav"
Another option: Using the windows media player active-x objects to play a sound. On Windows XP it was not installed by default but I think for the newer Windows versions it is. It also can play mp3 files:
call mediarunner.bat "C:\Windows\Media\Ring03.wav"
And one that is a little bit obscure - using the <bgsound> tag from internet explorer (which also can play mp3 files). Here's the script:
call soundplayer.bat "C:\Windows\Media\tada.wav"
And here's a way to use the BEL character to produce sound with easy to copy-paste code (I've called it a beeper.bat):
#echo off
setlocal
::Define a Linefeed variable
(set LF=^
%=-=%
)
for /f eol^=^%LF%%LF%^ delims^= %%A in (
'forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x07"'
) do echo(%%A
It's not possible to type the BEL directly in (for example) notepad.
To get it, type echo ^G>>yourbatch.bat on the command line (don't type ^ G, but <Control>-G, which will be shown as ^G on the screen). That puts a strange looking character to the end of your file. That's the BELcharacter 0x007 ("control-G"). Just copy/move it to any echo command, you like. Also
set /p "input=^Ggive value: "
is possible (where the ^G represents that strange char)
The following can be used to issue a beep
without pausing the script
without creating a new line.
without requiring the use of a non-printable character
Echo/| CHOICE /N 2> nul & rem BEL
It is a deliberate misuse of the choice command, that Echo's nothing via a pipe to Choice, causing a non-breaking error. STDERR is redirected to nul, and the default choice prompt is suppressed via the /N switch, meaning no new line is output.
If for some reason you wanted to reuse this annoying tone throughout a script, you could define it as a macro
Set "BEL=Echo/| CHOICE /N 2> nul"
%BEL%
#echo off
echo BEEP.BAT by CSS---
echo PRESS ANY KEY TO HEAR A BEEP...
PAUSE>NUL
ECHO
echo I BEEPED
PAUSE
there is an ASCII control code ^G after the echo. Just copy this code, and save it as ASCII/ANSI using a text editor.
use ECHO command to echo a CTRL G
I think the better solution is echoing a ^G to a file from the cmd prompt and then type that file from within the script, that way you don't need to include control characteres in the batch file itself:
C:\> echo ^G>beep.snd
Now there's an ASCII 007 char in the "beep.snd" file, then from your .bat file all you have to do is type it or copy to the screen:
type beep.snd
or
copy beep.snd con > nul
I tried all the options above in Win 10. I settled with this
powershell.exe [console]::beep(500,600)
So programmatically in node.js it would look like this (python or C would be similar)
require("child_process").exec("powershell.exe [console]::beep(500,600)");
A bit late to the party, but I find this variation on #npocmaka version works for me with Windows 10:
REM This captures the Bell as a variable.
for /f %%g in ('%__APPDIR__%forfiles.exe /p "%~dp0." /m "%~nx0" /c "cmd /c echo 0x07"') do set "bel=%%g"
REM This produces the Bell sound.
set /P "=%bel%"<NUL
This works for me..
there was a special character in line 4 which stackoverflow was omitting,
code's pasted here:
hashb.in/long
and line 5 and 6 can be used interchangeably of course.

In Windows cmd, how do I prompt for user input and use the result in another command?

I have a Windows .bat file which I would like to accept user input and then use the results of that input as part of the call to additional commands.
For example, I'd like to accept a process ID from the user, and then run jstack against that ID, putting the results of the jstack call into a file. However, when I try this, it doesn't work.
Here's my sample bat file contents:
#echo off
set /p id=Enter ID:
echo %id%
jstack > jstack.txt
and here's what shows up in jstack.txt:
Enter ID: Terminate batch job (Y/N)?
Try this:
#echo off
set /p "id=Enter ID: "
You can then use %id% as a parameter to another batch file like jstack %id%.
For example:
set /P id=Enter id:
jstack %id% > jstack.txt
The syntax is as such: set /p variable=[string]
Check out http://commandwindows.com/batch.htm or http://www.robvanderwoude.com/userinput.php for a more deep dive into user input with the different versions of Windows OS batch files.
Once you have set your variable, you can then go about using it in the following fashion.
#echo off
set /p UserInputPath=What Directory would you like?
cd C:\%UserInputPath%
note the %VariableName% syntax
set /p choice= "Please Select one of the above options :"
echo '%choice%'
The space after = is very important.
I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:
set /p Var1="Prompt String"
Without the prompt string in quotes, I get various results depending on the text.
#echo off
set /p input="Write something, it will be used in the command "echo""
echo %input%
pause
if i get what you want, this works fine. you can use %input% in other commands too.
#echo off
echo Write something, it will be used in the command "echo"
set /p input=""
cls
echo %input%
pause
There is no documented /prompt parameter for SETX as there is for SET.
If you need to prompt for an environment variable that will survive reboots, you can use SETX to store it.
A variable created by SETX won't be usable until you restart the command prompt. Neatly, however, you can SETX a variable that has already been SET, even if it has the same name.
This works for me in Windows 8.1 Pro:
set /p UserInfo= "What is your name? "
setx UserInfo "%UserInfo%"
(The quotation marks around the existing variable are necessary.)
This procedure allows you to use the temporary SET-created variable during the current session and will allow you to reuse the SETX-created variable upon reboot of the computer or restart of the CMD prompt.
(Edited to format code paragraphs properly.)
#echo off
:start
set /p var1="Enter first number: "
pause
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F :
call userInput.bat
There are two possibilities.
You forgot to put the %id% in the jstack call.
jstack %id% > jstack.txt
So the whole correct batch file should be:
#echo off
set /p id=Enter ID:
echo %id%
jstack %id% > jstack.txt
And/Or 2. You did put it in the code (and forgot to tell us in the question) but when you ran the batch file you hit the Enter key instead of typing an ID (say 1234).
What's happening is the result of these two mistakes:
jstack is supposed to be called with the id that you supply it.
But in your case (according to the code you supplied in the question) you called it without any variable. You wrote:
jstack > jstack.txt
So when you run jstack with no variable it outputs the following:
Terminate batch file Y/N?
Your second mistake is that you pressed Enter instead of giving a value when the program asked you: Enter ID:. If you would have put in an ID at this point, say 1234, the %id% variable would become that value, in our case 1234. But you did NOT supply a value and instead pressed Enter. When you don't give the variable any value, and if that variable was not set to anything else before, then the variable %id% is set to the prompt of the set command!! So now %id% is set to Enter ID: which was echoed on your screen as requested in the batch file BEFORE you called the jstack.
But I suspect you DID have the jstack %id% > jstack.txt in your batch file code with the %id (and omitted it by mistake from the question), and that you hit enter without typing in an id. The batch program then echoed the id, which is now "Enter ID:", and then ran jstack Enter ID: > jstack.txt
Jstack itself echoed the input, encountered a mistake and asked to terminate.
And all this was written into the jstack.txt file.
I have a little cmd I use when preparing pc to clients: it calls the user for input, and the rename the pc to that.
#ECHO "remember to run this as admin."
#ECHO OFF
SET /P _inputname= Please enter an computername:
#ECHO Du intastede "%_inputname%"
#ECHO "The pc will restart after this"
pause
#ECHO OFF
wmic computersystem where name="%COMPUTERNAME%" call rename name="%_inputname%"
shutdown -r -f
Dollar signs around the variable do not work on my Vista machine, but percent signs do.
Also note that a trailing space on the "set" line will show up between the prompt and user input.
Just added the
set /p NetworkLocation= Enter name for network?
echo %NetworkLocation% >> netlist.txt
sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.
Just to keep a default value of the variable. Press Enter to use default from the recent run of your .bat:
#echo off
set /p Var1=<Var1.txt
set /p Var1="Enter new value ("%Var1%") "
echo %Var1%> Var1.txt
rem YourApp %Var1%
In the first run just ignore the message about lack of file with the initial value of the variable (or do create the Var1.txt manually).
One other way which might be interesting. You can call a powershell script from where you can do pretty much anything, and send the data bach to cmd or do other stuff with something like this.
set var=myvar;
call "c:\input2.cmd" %var%.
Its kind of more flexible (You can send the data the same way with powershell).
So in your cmd, write this considering the ps script is in C::
PowerShell.exe -ExecutionPolicy unrestricted -Command "& {. C:\Input.ps1}"
And in your input.ps1 script, write this:
$var = Read-Host -Prompt "Your input"
Write-Host "Your var:",$var
#Do stuff with your variable

Why does batch file FOR fail when iterating over command output?

I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:
FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B
(There's a tab character after delims=)
This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),
it fails with 'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName' is not recognized as an internal or external command, operable program or batch file.' Running the "reg query" command alone works fine. Reg.exe is present in C:\Windows\System32.
I was able to work around the problem by changing the code to
REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims= " %%A IN (temp.txt) DO SET MyVariable=%%B
This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.
Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.
I would check:
The customer's role on the machine - are they an admin?
Where is reg.exe on the box - is there more than one copy of copy of reg.exe in the path?
Is there any locale difference on the customer's machine from the machines where this normally works?
Basically, enumerate everything that differs between this machine and machines where it works as expected. Include service packs, domain membership, etc.
Wow, that is odd.
If the same commands work when split into two lines, then I'd guess it has something to do with the way the command gets run in a subshell in the FOR command.
If you were really dying to figure out why it's dying in this particular case, you could run commands like "SET > envvars.txt" as the FOR command and compare that with the top shell.
Or maybe start off simple and try running the REG command via CMD /C to see if that does anything?
One quick guess here, what's the values of COMSPEC and SHELL ?
I had a similar situation to this. In my case it was a bad value in COMSPEC. I fixed that and the script started working as expected.
The /F switch needs command extensions to be turned on. Usually they are turned on by default, but I'd check that. On XP systems you can turn them on doing something like
cmd /e:on
or checking the registry under
HKCU\Software\Microsoft\Command Processor\EnableExtensions
Dunno about Windows Server.
Doing help for and help cmd could provide some hints as well.

Resources