Windows command file call

Команда CALL

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

Формат командной строки CALL:

CALL [диск:][путь]имя_файла [параметры]

параметры — набор параметров командной строки, необходимых пакетному файлу.

При включенном режиме расширенной обработки команд, CALL допускает использование меток в качестве адресата вызова. Применяется следующий синтаксис:

CALL :метка аргументы

При вызове создается новый контекст текущего пакетного файла с заданными аргументами, и управление передается на инструкцию, расположенную сразу после метки.

CALL C:\SCRIPTS\test.bat — вызвать командный файл C:\SCRIPTS\test.bat

CALL C:\SCRIPTS\test.bat param1 param2 — вызвать командный файл C:\SCRIPTS\test.bat и передать ему параметры param1 и param2

CALL :M1 param1 — вызвать процедуру, внутри текущего пакетного файла, по метке M1 и передать ей параметр param1

Для иллюстрации примеров использования команды CALL можно воспользоваться пакетным файлом, например под именем 1.bat следующего содержания:

CALL 2.bat IP 192.168.1.1
ECHO NEWSET = %NEWSET%

Файл 1.bat будет вызывать файл 2.bat и передавать ему 2 параметра — строки IP и 192.168.1.1. И вызываемый файл, например, выполнит создание новой переменной с именем NEWSET вида «IP = 192.168.1.1» Для этого в файле 2.bat используется команда SET:

После выполнения файла 2.bat будет выполнен возврат в файл 1.bat и команда ECHO выведет на экран значение переменной NEWSET, сформированное вызываемым командным файлом.

При использовании вызова процедуры по метке в командном файле, есть некоторые особенности. Для примера, создадим командный файл, в котором имеется вызываемая подпрограмма, которая должна вычислить сумму двух чисел, передаваемых ей в качестве параметров, и присвоить результат переменной Rezult :

REM вызов подпрограммы для суммирования чисел 100 и 2
call :M1 100 2
REM Вывод результата
echo Результат = %Rezult%
pause
exit

:M1
SET /A Rezult=%1+%2
exit /b

Windows commands

All supported versions of Windows (server and client) have a set of Win32 console commands built in.

This set of documentation describes the Windows Commands you can use to automate tasks by using scripts or scripting tools.

Prerequisites

The information that is contained in this topic applies to:

  • Windows Server 2019
  • Windows Server (Semi-Annual Channel)
  • Windows Server 2016
  • Windows Server 2012 R2
  • Windows Server 2012
  • Windows Server 2008 R2
  • Windows Server 2008
  • Windows 10
  • Windows 8.1

Command shell overview

The Command shell was the first shell built into Windows to automate routine tasks, like user account management or nightly backups, with batch (.bat) files. With Windows Script Host you could run more sophisticated scripts in the Command shell. For more information, see cscript or wscript. You can perform operations more efficiently by using scripts than you can by using the user interface. Scripts accept all Commands that are available at the command line.

Windows has two command shells: The Command shell and PowerShell. Each shell is a software program that provides direct communication between you and the operating system or application, providing an environment to automate IT operations.

PowerShell was designed to extend the capabilities of the Command shell to run PowerShell commands called cmdlets. Cmdlets are similar to Windows Commands but provide a more extensible scripting language. You can run Windows Commands and PowerShell cmdlets in Powershell, but the Command shell can only run Windows Commands and not PowerShell cmdlets.

For the most robust, up-to-date Windows automation, we recommend using PowerShell instead of Windows Commands or Windows Script Host for Windows automation.

You can also download and install PowerShell Core, the open source version of PowerShell.

Incorrectly editing the registry may severely damage your system. Before making the following changes to the registry, you should back up any valued data on the computer.

Читайте также:  Закрыть файл командой windows

To enable or disable file and directory name completion in the Command shell on a computer or user logon session, run regedit.exe and set the following reg_DWOrd value:

To set the reg_DWOrd value, use the hexadecimal value of a control character for a particular function (for example, 0 9 is Tab and 0 08 is Backspace). User-specified settings take precedence over computer settings, and command-line options take precedence over registry settings.

Command-line reference A-Z

To find information about a specific command, in the following A-Z menu, click the letter that the command starts with, and then click the command name.

Windows command file call

Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call

Call has no effect at the command prompt when it is used outside of a script or batch file.

Syntax

Parameters

] Specifies the location and name of the batch program that you want to call. The parameter is required, and it must have a .bat or .cmd extension. Specifies any command-line information required by the batch program. : Specifies the label that you want a batch program control to jump to. Specifies the command-line information to be passed to the new instance of the batch program, beginning at : . /? Displays help at the command prompt.

Batch parameters

The batch script argument references (%0, %1, . ) are listed in the following tables.

Using the %* value in a batch script refers to all the arguments (for example, %1, %2, %3. ).

You can use the following optional syntaxes as substitutions for batch parameters (%n):

Batch Parameter Description
%

1

Expands %1 and removes surrounding quotation marks.
%

f1

Expands %1 to a fully qualified path.
%

d1

Expands %1 to a drive letter only.
%

p1

Expands %1 to a path only.
%

n1

Expands %1 to a file name only.
%

x1

Expands %1 to a file name extension only.
%

s1

Expands %1 to a fully qualified path that contains short names only.
%

a1

Expands %1 to the file attributes.
%

t1

Expands %1 to the date and time of file.
%

z1

Expands %1 to the size of the file.
%

$PATH:1

Searches the directories listed in the PATH environment variable, and expands %1 to the fully qualified name of the first directory found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string.

The following table shows how you can combine modifiers with the batch parameters for compound results:

Batch Parameter with Modifier Description
%

dp1

Expands %1 to a drive letter and path only.
%

nx1

Expands %1 to a file name and extension only.
%

dp$PATH:1

Searches the directories listed in the PATH environment variable for %1, and then expands to the drive letter and path of the first directory found.
%

ftza1

Expands %1 to display output similar to the dir command.

In the above examples, %1 and PATH can be replaced by other valid values. The %

syntax is terminated by a valid argument number. The %

modifiers cannot be used with %*.

Remarks

Using batch parameters:

Batch parameters can contain any information that you can pass to a batch program, including command-line options, file names, the batch parameters %0 through %9, and variables (for example, %baud%).

Using the parameter:

By using call with the parameter, you create a new batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement. The second time the end of the batch file is encountered, the batch script is exited.

Using pipes and redirection symbols:

Do not use pipes (|) or redirection symbols ( or > ) with call.

Making a recursive call

You can create a batch program that calls itself. However, you must provide an exit condition. Otherwise, the parent and child batch programs can loop endlessly.

Working with command extensions

If command extensions are enabled, call accepts as the target of the call. The correct syntax is call :

вызывает call

Вызывает одну пакетную программу из другой без остановки родительской пакетной программы. Calls one batch program from another without stopping the parent batch program. Команда Call принимает метки в качестве целевого объекта вызова The call command accepts labels as the target of the call

Вызов не оказывает влияния на командную строку, если она используется вне скрипта или пакетного файла. Call has no effect at the command prompt when it is used outside of a script or batch file.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
[ :][

] Указывает расположение и имя пакетной программы, которую необходимо вызвать. Specifies the location and name of the batch program that you want to call. Параметр является обязательным и должен иметь расширение BAT или cmd. The parameter is required, and it must have a .bat or .cmd extension. Указывает все данные командной строки, необходимые для пакетной программы. Specifies any command-line information required by the batch program. : Указывает метку, к которой должен перейти элемент управления программой пакетной службы. Specifies the label that you want a batch program control to jump to. Указывает сведения командной строки, передаваемые в новый экземпляр программы пакетной службы, начиная с : . Specifies the command-line information to be passed to the new instance of the batch program, beginning at : . /? /? Отображение справки в командной строке. Displays help at the command prompt.

Параметры пакета Batch parameters

Ссылки на аргумент скрипта пакетной службы (%0, %1. ) перечислены в следующих таблицах. The batch script argument references (%0, %1, . ) are listed in the following tables.

Использование значения % * в пакетном скрипте означает все аргументы (например, %1, %2, %3. ). Using the %* value in a batch script refers to all the arguments (for example, %1, %2, %3. ).

Можно использовать следующие необязательные синтаксисы в качестве подстановок для пакетных параметров (% n): You can use the following optional syntaxes as substitutions for batch parameters (%n):

Параметр Batch Batch Parameter Описание Description
%

1

Развертывает %1 и удаляет окружающие кавычки. Expands %1 and removes surrounding quotation marks.
%

f1

Расширение %1 до полного пути. Expands %1 to a fully qualified path.
%

d1

Расширение %1 до буквы диска. Expands %1 to a drive letter only.
%

p1

Развертывает %1 только для пути. Expands %1 to a path only.
%

n1

Расширение %1 только на имя файла. Expands %1 to a file name only.
%

x1

Развертывает %1 только для расширения имени файла. Expands %1 to a file name extension only.
%

s1

Расширение %1 до полного пути, содержащего только короткие имена. Expands %1 to a fully qualified path that contains short names only.
%

a1

Развертывает %1 для атрибутов файла. Expands %1 to the file attributes.
%

t1

Увеличивает %1 до даты и времени файла. Expands %1 to the date and time of file.
%

z1

Расширение %1 до размера файла. Expands %1 to the size of the file.
%

$PATH:1

Выполняет поиск в каталогах, перечисленных в переменной среды PATH, и разворачивает %1 до полного имени найденного первого каталога. Searches the directories listed in the PATH environment variable, and expands %1 to the fully qualified name of the first directory found. Если имя переменной среды не определено или файл не найден при поиске, то этот модификатор разворачивается до пустой строки. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string.

В следующей таблице показано, как можно объединить модификаторы с пакетными параметрами для составных результатов. The following table shows how you can combine modifiers with the batch parameters for compound results:

Параметр Batch с модификатором Batch Parameter with Modifier Описание Description
%

dp1

Расширение %1 до буквы диска и пути. Expands %1 to a drive letter and path only.
%

nx1

Развертывает %1 только для имени файла и расширения. Expands %1 to a file name and extension only.
%

точка DP $ PATH: 1 %

dp$PATH:1

Выполняет поиск в каталогах, перечисленных в переменной среды PATH для %1, а затем разворачивается на букву диска и путь к первому найденному каталогу. Searches the directories listed in the PATH environment variable for %1, and then expands to the drive letter and path of the first directory found.
%

ftza1

Разворачивает %1 для вывода выходных данных, аналогичных команде dir . Expands %1 to display output similar to the dir command.

В приведенных выше примерах %1 и Path могут быть заменены другими допустимыми значениями. In the above examples, %1 and PATH can be replaced by other valid values. %

Синтаксис завершается допустимым номером аргумента. The %

syntax is terminated by a valid argument number. %

Модификаторы нельзя использовать с % *. The %

modifiers cannot be used with %*.

Комментарии Remarks

Использование параметров пакетной службы: Using batch parameters:

Пакетные параметры могут содержать любые сведения, которые можно передать в пакетную программу, включая параметры командной строки, имена файлов, параметры пакета %0%9 и переменные (например, % бод%). Batch parameters can contain any information that you can pass to a batch program, including command-line options, file names, the batch parameters %0 through %9, and variables (for example, %baud%).

С помощью параметра: Using the parameter:

Используя вызов с параметром, вы создаете новый контекст файла пакета и передаете управление оператору после указанной метки. By using call with the parameter, you create a new batch file context and pass control to the statement after the specified label. При первом обнаружении конца пакетного файла (то есть после перехода к метке) управление возвращается оператору после оператора Call . The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement. При втором обнаружении конца пакетного файла пакетный сценарий завершается. The second time the end of the batch file is encountered, the batch script is exited.

Использование каналов и символов перенаправления: Using pipes and redirection symbols:

Не используйте каналы (|) или символы перенаправления ( или > ) с вызовом. Do not use pipes (|) or redirection symbols ( or > ) with call.

Выполнение рекурсивного вызова Making a recursive call

Можно создать пакетную программу, которая вызывает саму себя. You can create a batch program that calls itself. Однако необходимо указать условие выхода. However, you must provide an exit condition. В противном случае родительские и дочерние пакетные программы могут подбираться бесконечно. Otherwise, the parent and child batch programs can loop endlessly.

Работа с расширениями команд Working with command extensions

Если расширения команд включены, вызов принимает в качестве цели вызова. If command extensions are enabled, call accepts as the target of the call. Правильный синтаксис: call : The correct syntax is call :

Читайте также:  Проводник windows как finder
Оцените статью