Choice для windows 7

В этой статье я расскажу о команде Choice и рассмотрю пример ситуации, в которой она может пригодиться.Как работает команда Choice

Команда Choice позволяет сделать командные файлы интерактивными. Чтобы понять, как она работает, рассмотрим базовый вариант команды:

Choice /M «Продолжить»

Если ввести эту команду в окне командной строки и нажать [Enter], появится следующее сообщение:

Продолжить [Y,N]?

Как видите, текст, указанный после параметра /m, превращается в сообщение. Выбор [Y,N]? команда Choice добавляет автоматически, и это варианты по умолчанию. Если нажать [Y], команда возвращает значение 1, если [N] – значение 2. Значение задается с помощью переменной среды Errorlevel.

Теперь, когда вы понимаете базовый принцип, давайте рассмотрим более полноценный пример.

Choice /M «Хотите ли вы продолжить?»
If Errorlevel 2 Goto No
If Errorlevel 1 Goto Yes
Goto End

:No
Echo Вы выбрали Нет
Goto End

:Yes
Echo Вы выбрали Да
:End

В этом примере я использовал конструкцию If Errorlevel, чтобы определить значение переменной среды, конструкцию Goto, чтобы задать направление выполнения командного файла по указанному пути и команду Echo, чтобы вывести сообщение о результатах. Обратите внимание: при использовании конструкции If Errorlevel в командной программе числа следует располагать по убывающей.Параметры

Выше приведен пример базовой команды Choice. С использованием дополнительных параметров можно создавать более сложные команды. Ниже приводится официальное описание параметров команды Choice от Microsoft:

CHOICE [/C список] [/N] [/CS] [/T тайм-аут /D элемент] [/M текст]

Использование команды Choice в Windows 7

Пример реального использования

Теперь, когда вы представляете, как работает команда Choice, давайте рассмотрим пример реальной ситуации, в которой эта команда может облегчить использование командного файла.

Диагностика и разрешение проблем, связанных с TCP/IP, в сети Windows может оказаться нелегкой задачей. Сделать ее проще позволяет команда IP Configuration (IPConfig), которая предоставляет подробные сведения о сетевых настройках Windows. Эти данные можно использовать для проверки сетевых соединений и настроек, что в сочетании с другими инструментами помогает диагностировать и устранять неполадки, связанные с TCP/IP, в сети Windows.

К сожалению, команда IPConfig имеет массу параметров, причем некоторые из них очень длинные, так что их нелегко запомнить и правильно ввести. Чтобы упростить задачу, я создал командный файл, показанный на рис. A (если хотите, можете его

скачать). Странные символы я скопировал из таблицы символов: они создают симпатичную рамку, как показано на рис. B.

Использование команды Choice в Windows 7

Рисунок A. Файл «IPC.bat», созданный с использованием команды Choice, облегчает применение длинных параметров команды IPConfig.

Чтобы запустить файл, откройте окно командной строки в нужной папке и введите IPC. Появится аккуратное меню, показанное на рис. B. С помощью команды Choice можно легко выбрать и запустить нужный вариант IPConfig с распространенными параметрами. Достаточно просто ввести определенную цифру, и команда запустится автоматически.

Использование команды Choice в Windows 7

Рисунок B. Изучив меню, просто введите нужную цифру, чтобы запустить соответствующую команду IPConfig.

А что думаете вы?

Приходится ли вам создавать и использовать командные файлы на регулярной основе? Будете ли вы пользоваться командой Choice? Скачаете ли вы файл «IPC.bat»? Поделитесь своим мнением в комментариях!

Автор: Greg Shultz
Перевод

SVET

Оцените статью: Голосов

Windows 7 / Getting Started


The Choice command lets you add interactive processing to batch files. Whether you use this
option depends on the kind of automation you want to add to your processing tasks. Most of the
automation you create for optimization tasks won’t require any kind of interactivity because you
already know how you want the task performed based on experience you obtained performing the
task manually. However, sometimes you do need to add some interactivity. For example, you might
run the command one way on Friday and a different way the rest of the week. The Choice command
can also help you add safeguards that ensure the user understands the ramifications of performing
a certain task before they actually do it. Vista and Server Core change the Choice command significantly,
breaking many batch files. The Vista and Server Core form of the Choice command differs
not in arguments, but in how you combine those arguments at the command line. Here’s the command line for Vista and Server Core:

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]

The changes make the command clearer, but they break existing batch files in a way that you
can’t easily fix. The new /CS command line switch lets you make choices case sensitive, so you can
have 26 additional menu choices. However, notice that /T no longer takes both a default option and
a timeout value. The new form requires that you provide a choice using the /D command line
switch instead. You must also provide the /M command line switch to specify optional text. The following
sample code performs the same task, but the first form works in Windows XP and earlier, while the second form works in Vista and Server Core.

Old Choice Command Form
CHOICE /C:N /N /T:N,15
Vista and Server Core Choice Command Form
CHOICE /C N /N /T 15 /D N

NOTE: Vista and Server Core provide alternatives for the Choice command. The TimeOut utility
provides a specific timeout value without requiring the user to make a choice. You can learn more
about this utility in the «Using the TimeOut Utility» section of the tutorial. The WaitFor utility
lets you use signaling between systems or applications on the same system. One application
sends a signal and another reacts when it receives the signal. You can learn more about this utility
in the «Using the WaitFor Utility» section of the tutorial.

When you use Choice by itself, it displays a simple [Y,N] prompt that doesn’t accomplish much
unless you also provide an Echo command to describe what the user should say yes or no to.
Normally, you’ll combine the Choice command with one or more arguments. Listing-1 shows a
simple example of the Choice command at work.

Listing-1: Using the Choice Command

Echo Off

REM Keep repeating until the user enters E.
:Repeat

REM Display the choices.
Choice /C DCE /N /T 15 /D E /M "Choose an option (D)isplay, (C)opy, or (E)nd."
REM Act on the user choice.
If ErrorLevel 3 Goto End
If ErrorLevel 2 Goto Copy
If ErrorLevel 1 Goto Display

REM Copy the file.
:Copy
Echo You chose to copy the file.
Goto Repeat

REM Display the file.
:Display
Echo You chose to display the file.
Goto Repeat

REM End the batch processing.
:End
Echo Goodbye
Echo On

The code begins by creating a repeat label so the batch file continues working until the user
specifically stops it. Next, the code uses the Choice command to display the choices to the user. The
/C switch tells Choice that the valid options are D, C, or E instead of the default Y or N. Because
the text specifically defines the characters that the batch file expects, the batch file uses the /N
switch to suppress displaying the valid key choices on the command line. The /T command line
switch tells Choice to automatically choose E after 10 seconds. The /D command line switch provides
the default choice of E. Finally, the /M command line switch provides the message displayed to the user.

Although this batch file doesn’t actually do anything with a file, it shows how you’d set up the
batch file to process the user choice. Notice that the batch file uses the ErrorLevel clause of the If
statement to detect the user choice. The ErrorLevel clause detects every choice lower than the user
selection, so you must place the values in reverse order, as shown. In addition, you must specifically
set the batch file to go to another location because it will process all other statements after the current error level.

The processing code simply displays a string telling you what choice the user made. Normally,
you’d add tasks that the batch file should perform based on the user’s selection. Notice that the
copy and display selections tell the batch file to go back to the Repeat label. This is the most common
technique for creating a menu loop in a batch file. The batch file ends by telling the user goodbye and turning echo back on.

Using the Echo Command

The command line uses the term echo to describe the process where the system echoes (repeats)
every command in a batch file to the command line. Echo provides a means of seeing which command
the system is processing. However, echo can become confusing for users who aren’t aware
of or don’t care about the commands that are executing. In addition, echo can disrupt visual effects,
such as menu systems, that you create. The Echo command has two forms. The first form

ECHO [{ON | OFF}]

displays the echo status when you don’t include any arguments. The ON argument turns on echo so
you can see the commands, and the OFF argument turns off echo so you can create visual effects.
You can precede the Echo command with the @ sign so it doesn’t appear as one of the commands.
@Echo OFF would turn echo off without displaying the echo command at the command prompt.
The second form of echo

ECHO [message]

lets you display a message. Simply type the text you want to see after the Echo command. In this
case, the system won’t display the Echo command, just the message you want to display. Don’t use
the @ sign with this form of the Echo command or the user won’t see the message.

Using the Exit Command

Most people associate the Exit command with closing the current command window. Using Exit
alone will close the command window. However, you can also use this command within a batch
file to exit the batch file. To perform this task, you must use one or both of the following optional Exit arguments.

/B Specifies that you want to exit a batch file, rather than the current command line session. If
you don’t specify this command line switch, the command window closes, even when you issue the Exit command from a batch file.

ExitCode Defines an exit code for the batch file. The default exit code is 0, which normally signifies
success. You can use exit codes to alert the caller to errors or special conditions. The exit
codes aren’t defined by the system, so you can define any set of exit codes that you deem necessary for your application.

Using the ForFiles Utility

The ForFiles utility provides a means of looping through a list of files and performing actions on
those files one at a time. For example, you might want to process all files that someone has changed
since a certain date. In most respects, this loop method works precisely the same as the For command
described in the «Using the For Command» section of the tutorial. This command uses the following syntax:

FORFILES [/P pathname] [/M searchmask] [/S] [/C command]
[/D [+ | -] {MM/dd/yyyy | dd}]

The following list describes each of the command line arguments.

/P pathname Specifies the starting point for a search. The path is the starting folder in the
search. The default setting uses the current directory as the starting point.

/M searchmask Defines a search mask for the files. You can use the asterisk (*) and question
mark (?) as wildcard characters, just as you would when using the Directory command. The
default setting searches for all files in the target directory.

/S Searches all of the subdirectories of the specified directory.

/C command Specifies the command you want to execute for each file. Always wrap the command
in double quotes to ensure it isn’t interpreted as part of the ForFile command. The default
command is «cmd /c echo @file». Always precede internal command processor command with
cmd /c. The following list describes the variables that you can use as part of the command.

@file Returns the name of the file, including the file extension.
@fname Returns the name of the file without the extension.
@ext Returns only the file extension.
@path Returns the full path of the file. This information includes the drive as well as the actual path.
@relpath Returns the relative path of the file. The relative path begins at the starting folder.
@isdir Specifies whether the file type is a directory. True indicates a directory entry.
@fsize Indicates the size of the file in bytes.
@fdate Indicates the date that someone last modified the file.
@ftime Indicates the time that someone last modified the file.

TIP: You can include special characters in a command by using the 0xHH format where HH is a
hexadecimal number. For example, you can specify a tab by typing 0x09.
/D date Selects files that have a last modified date within the specified range. You specify a
specific date using the month/day/year (mm/dd/yyyy) format. Add a plus sign if you want
files after the specified date or a minus sign if you want files before the specified date. For example,
/D -01/01/2008 would select all files modified before January 1, 2008. You can also specify
a relative date by providing a positive or negative number. For example, /D -7 would select all
files modified within the last seven days. The /D command line switch accepts any number between 0 and -32,768.

I have a plenty of Windows interactive batch files that are using choice.com tool as a helper when I need some input from the user, for example:

:: ***********
:: * BEGIN   *
:: *********** 
:begin
color 0e
cls
echo.
echo **********************************************
echo You started interactive batch script.... 
echo **********************************************
echo Select server:
echo (1) EUROPE 
echo (2) ASIA
echo (3) US
echo (4) ALL THREE
echo (5) EXIT 
echo.

..\util\choice /C:12345 Pick one

if errorlevel 5 goto end
if errorlevel 4 goto all
if errorlevel 3 goto US
if errorlevel 2 goto ASIA
if errorlevel 1 goto EUROPE

:EUROPE
... do some stuff ...
goto end

:ASIA
... do some stuff ...
goto end

:US
... do some stuff ...
goto end

:ALL
... do some stuff ...
goto end

:: END
:END

Choice.com is 16-bit application that can not run on Windows x64. The simplest workaround that I found is to use SET /P command. It’s a little bit of more code to write, but it’s quite trivial and does not hurt script readability. We can rewrite above script as:

:: ***********
:: * BEGIN   *
:: *********** 
:begin
color 0e
cls
echo.
echo **********************************************
echo You started interactive batch script.... 
echo **********************************************
echo Select server:
echo (1) EUROPE 
echo (2) ASIA
echo (3) US
echo (4) ALL THREE
echo (5) EXIT 
echo.

set choice=
set /P choice="Select 1..5: "

::
:: I used ~0,1 to "substring" first character from the input
::
if not '%choice%'=='' set choice=%choice:~0,1%

if /I '%choice%'=='1' goto europe
if /I '%choice%'=='2' goto asia
if /I '%choice%'=='3' goto all
if /I '%choice%'=='5' goto end

::
:: if we came here then we know that user entered 
::
echo "%choice%" is not a valid option
pause
echo.
goto begin


:EUROPE
... do some stuff ...
goto end

:ASIA
... do some stuff ...
goto end

:US
... do some stuff ...
goto end

:ALL
... do some stuff ...
goto end

:: END
:END

Rob van der Woude's Scripting Pages

The CHOICE command was introduced in MS-DOS 6 and is still available in MS-DOS 7 (Windows 95/98).

In Windows NT 4, 2000 and XP, CHOICE is no longer a part of the standard distribution.
It is, however, available as part of the Windows NT 4 Resouce Kit.
On the other hand, if you still have that old unused MS-DOS 6 or Windows 95/98 version lying around, you can use the CHOICE.COM from that version instead. (*)
Just copy it to a directory that is in your PATH.

Note: 16-bit DOS versions will not work in 64-bit Windows versions.

CHOICE is available again in Windows Vista and later versions.

Syntax:

CHOICE [ /C choices ] [ /N ] [ /CS ] [ /T timeout /D choice ] [ /M text ]
 
Description:
     This tool allows users to select one item from a list of choices and returns the index of the selected choice.
Parameter List:
 
     /C choices      Specifies the list of choices to be created.
Default list for English versions is YN
  /N   Hides the list of choices in the prompt.
The message before the prompt is displayed and the choices are still enabled.
  /CS   Enables case-sensitive choices to be selected.
By default, the utility is case-insensitive.

Note: DOS and NT Resource Kit versions use /S instead

  /T timeout   The number of seconds to pause before a default choice is made.
Acceptable values are from 0 to 9999.
If 0 is specified, there will be no pause and the default choice is selected.

Note: DOS and NT Resource Kit versions use /T:default,timeout instead.

  /D default   Specifies the default choice after timeout seconds.
Character must be in the set of choices specified by /C option and must also specify timeout with /T.

Note: DOS and NT Resource Kit versions use /T:default,timeout instead.

  /M text   Specifies the message to be displayed before the prompt.
If not specified, the utility displays only a prompt.
 
     The ERRORLEVEL is set to the offset of the index of the key that was selected from the set of choices.
The first choice listed returns a value of 1, the second a value of 2, and so on.
If the user presses a key that is not a valid choice, the tool sounds a warning beep.
If tool detects an error condition, it returns an ERRORLEVEL value of 255.
If the user presses CTRL+BREAK or CTRL+C, the tool returns an ERRORLEVEL value of 0.
When you use ERRORLEVEL parameters in a batch program, list them in decreasing order.

Examples:

  • The command:

    CHOICE /M "Do yo really want to quit"

    Will display the following line:

    Do yo really want to quit? [YN]

    If the user presses Y, CHOICE exits with return code («errorlevel») 1 (1st character in choices), if the user presse N, CHOICE exits with return code 2 (2nd character in choices).

  • CHOICE /C ABCDN /N /T 10 /D C /M "Format drive A:, B:, C:, D: or None?"
    IF ERRORLEVEL 1 SET DRIVE=drive A:
    IF ERRORLEVEL 2 SET DRIVE=drive B:
    IF ERRORLEVEL 3 SET DRIVE=drive C:
    IF ERRORLEVEL 4 SET DRIVE=drive D:
    IF ERRORLEVEL 5 SET DRIVE=None
    ECHO You chose to format %DRIVE%

    The CHOICE command in this example will prompt the user with the following line:

    Format drive A:, B:, C:, D: or None?

    If the user presses C, CHOICE exits with a return code («errorlevel») 3 (3rd character in choices).
    The IF ERRORLEVEL checks for 1, 2 and 3 are true (see the errorlevel page for an explanation of errorlevels), so the variable DRIVE will be set to «drive A:» first, then to «drive B:», and finaly to «drive C:».
    So the ECHO command will display the line:

    You chose to format drive C:

    By the way, in Windows NT 4 this won’t work, since the SET command itself will set an errorlevel (usually 0)!
    However, Windows NT makes it easy by storing the latest errorlevel in the environment variable ERRORLEVEL:

    SET DRIVENUM=%ERRORLEVEL%
    IF %DRIVENUM% EQU 1 SET DRIVE=drive A:
    IF %DRIVENUM% EQU 2 SET DRIVE=drive B:
    IF %DRIVENUM% EQU 3 SET DRIVE=drive C:
    IF %DRIVENUM% EQU 4 SET DRIVE=drive D:
    IF %DRIVENUM% GTR 4 SET DRIVE=None

    will do the trick.
    More details can be found here.

At the bottom of my errorlevel page you can find an example that uses CHOICE to convert redirected output to an errorlevel.

On my wait page CHOICE’s time-out option (/T) is used to insert a delay in batch files.

An ingenious way to use CHOICE is demonstrated by Laurence Soucy’s version of BootDriv.bat.

CHOICE can also be used to strip or replace certain characters from text strings, as explained on my Batch HowTo page, the CD-ROM example of my Solutions found at alt.msdos.batch page, and in the GetPorts example.

My PMCHOICE for NT, written in both KiXtart and batch, gives NT users almost the same functionality.
I haven’t figured out a way to implement the time-out period in KiXtart, though pressing Enter will result in the default value, if specified.

The more recently written SecondChoice.bat (for Windows XP and later) also supports pressing Enter for the default value, and it is entirely self-contained, pure batch only.

My CHOICE.EXE for OS/2, written in Rexx and compiled by RXCLS, gives OS/2 users the same functionality.
To use the /T switch you would need Quercus Systems’ RexxLib, though, which unfortunately is no longer available.

I also «ported» the CHOICE command to Rexx and Perl, though the latter does have some limitations.


page last modified: 2016-03-03; loaded in 0.0016 seconds

Загрузить PDF

Загрузить PDF

Вы действительно хороши в программировании командных файлов, лишь не знаете, как сделать меню с выбором «да», «нет» или Выбор 1, 2 или 3? Вы пришли в нужное место!

  1. Step 1 Нажмите Пуск>Выполнить» src=»https://www.wikihow.com/images_en/thumb/8/8c/Create-Options-or-Choices-in-a-Batch-File-Step-1-Version-2.jpg/v4-460px-Create-Options-or-Choices-in-a-Batch-File-Step-1-Version-2.jpg» width=»460″ height=»345″></p>
<div class= Картинка с сайта: ru.wikihow.com

  • Step 2 Введите "cmd" (без кавычек)

  • Step 3 Введите "edit"

  • Step 4 Введите следующие команды.

    После каждой нажимайте enter. Все, что в скобках, вводить НЕ надо, это примечания с пояснениями.

  • Step 5 @echo off (Эта...

    @echo off (Эта команда ‘спрячет’ возможность ввода команд – по желанию, но мы рекомендуем использовать ее)

  • Step 6 cls (Спрячет все,...

    cls (Спрячет все, что выше, – по желанию, но если вы хотите, чтобы все выглядело упорядоченным – рекомендуем)

  • Step 7 :start

  • Step 8 echo.

  • Step 9 echo Choice 1 ("Choice 1" можно переименовать как вам нужно)

  • Step 10 echo Choice 2

  • Step 11 echo Choice 3 (Вставьте столько вариантов, сколько вам нужно).

  • Step 12 Введите "set /p choice=(Здесь вставьте вопрос или команду, например "Yes or no?"

    )

  • Step 13 if not '%choice%'== set choice=%choice:

    ~0,1%

  • Step 14 if '%choice%'=='1' goto :choice1

  • Step 15 if '%choice%'=='2' goto :choice2

  • Step 16 (Продолжайте по этому...

    (Продолжайте по этому примеру, пока не достигнете нужного вам количества вариантов. Затем введите:)

  • Step 17 echo "%choice%" не является допустимым вариантом.

    Пожалуйста, попробуйте снова.

  • Step 18 echo.

  • Step 19 goto start

  • Step 20 После этого вводите:

  • Step 21 :choice1

  • Step 22 (команды для выполнения)

  • Step 23 goto end

  • Step 24 :choice2

  • Step 25 (команды)

  • Step 26 goto end

  • Step 27 :choice3

  • Step 28 (команды)

  • Step 29 goto end

  • Step 30 Продолжайте, пока не введете нужное вам количество команд.

  • Step 31 :end

  • Step 32 pause

  • Step 33 exit

  • 34

    Сохраните как файл с расширением .bat. Чтобы проверить командный файл, дважды щелкните по нему.

    Реклама

  • Пример

    @ECHO off
    cls
    :start
    ECHO.
    ECHO 1. Print Hello
    ECHO 2. Print Bye
    ECHO 3. Print Test
    set /p choice=Введите номер, чтобы вывести текст.
    rem if not '%choice%'=='' set choice=%choice:~0;1% ( не используйте эту команду, так как она берет только первую цифру, если вы вводите несколько. Например, если введете число 23455666, будет выбрана только цифра 2 и вы получите "bye"
    if '%choice%'=='' ECHO "%choice%"  не является допустимым вариантом, попробуйте снова
    if '%choice%'=='1' goto hello
    if '%choice%'=='2' goto bye
    if '%choice%'=='3' goto test
    ECHO.
    goto start
    :hello
    ECHO HELLO
    goto end
    :bye
    ECHO BYE
    goto end
    :test
    ECHO TEST
    goto end
    :end
    pause
    exit
    

    Советы

    • Для более подробной информации введите в командной строке /help.
    • Вы можете поменять :choice1 на любое другое слово, но придерживайтесь его до конца файла.
    • Для более подробной информации введите в командной строке choice /?.
    • Редактор команд в командной строке не работает в Windows 8. Эти команды доступны для windows XP/Vista/Windows 7.

    Реклама

    Предупреждения

    • Если вы не уверены в том, что делаете, не используйте команды.
    • Команды, которые вы используете бездумно, могут повредить ваш компьютер.

    Реклама

    Об этой статье

    Эту страницу просматривали 26 218 раз.

    Была ли эта статья полезной?

    Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии
  • Как скопировать dvd диск на компьютер windows 10
  • Создание загрузчика для windows 10
  • Windows whistler build 2428
  • Windows bios flash utility не устанавливается
  • Инструменты для управления процессами windows