Windows cmd window options

CMD Options

CMD has several command-line options. Although you don’t often need to use these options, you might want to be familiar with them. To start the command shell with alternative settings, you can type start cmd with additional parameters or run cmd from within a shortcut, batch file, and so on.

The syntax of the CMD command itself is as follows:

cmd [/a | /u] [/q] [/d] [/t:fg] [/e:on|off] [/f:on|off] [/v:on|off] [[/s] [/c | /k] [command]

You can give CMD a specific command line to execute, or you can start it without a command. In the latter case, it repeatedly prompts for commands.

The options are described here.The features noted with an asterisk are discussed in the following sections:

Options Descriptions
/a Causes standard output to use ANSI encoding.
/u Causes standard output to use Unicode encoding.
/q Turns the batch file echo default to off.
/d Disables execution of AutoRun commands defined in the Registry. Use this if a rogue program (or you) sets up a bad AutoRun entry.
/t:bf Sets the background (window) and foreground (text) colors for the window. For example, /t:80 specifies black text on a gray background. The color values are listed in Table below.
/e Enables or disables the command extensions.
/f Enables or disables the file and directory name completion feature.
/v Enables delayed environment variable expansion of !varname!
/s Modifies the treatment of quotation marks on the command line
/c Executes the command(s) in command and then quits.
/k Executes the command(s) in command and then reads further commands from the standard input until end of file or until the exit command is received.

If used, the /c or /k option must appear immediately before the command string. Anything after /c or /k is treated as part of the command to be run, rather than an argument to CMD.

Several nonstandard command-line arguments are also recognized to maintain compatibility with batch files written for Windows NT 4.0:

Arguments Description
/x Same as /e:on. Enables command extensions.
/y Same as /e:off. Disables command extensions.
/r Same as /c. Executes command and quits.

The color codes used with /t are listed in Table below.

CMD.exe

Start a new CMD shell and (optionally) run a command/executable program.

At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives File and folder name completion.

These key-strokes will display the first matching path. Thereafter, repeated pressing of the same control key will cycle through the list of matching paths. Pressing SHIFT with the control key will move through the list backwards.

If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator ‘&’ or ‘&&’ are accepted if surrounded by quotes.

In Windows Explorer, you can type » cmd » in the address bar to open a prompt at the current location.
For more detail about the CMD shell: QuickEdit, handing quotes, max line length etc, see the CMD Syntax page.

ErrorLevel

CMD /C will return an errorlevel, for example CMD /c dir Z: where the drive Z: does not exist, will return %errorlevel% = 1 to the calling CMD shell.

Launching CMD/batch files from a UNC path

While most command line utilities do fully support UNC paths, they cannot be set as the current directory. Launching a batch file from a UNC path will implicitly run CMD.exe with that UNC path, this will often return the error: path is an invalid current directory path. UNC paths are not supported. Defaulting to Windows directory.
This can be dangerous if your batch file makes any assumptions about the current directory,
e.g. if it includes the line DEL *.ico , that will delete .ico files from the Windows directory instead of the folder where the batch file resides.
If you are confident that the batch file won’t be affected by this, you can suppress the error in one of two ways: Add a CLS command as the first line of the batch script, or add the registry key DisableUNCCheck as described in Q156276

Alternatively start the batch file with pushd «%

dp0″
That will change directory to your batch file location ( %0 ), and for UNC paths it will auto-create a temporary drive map.

Launching CMD/batch files from PowerShell

When calling CMD from PowerShell the —% operator can be used to control when $ symbols and quoted expressions will be interpreted/expanded by PowerShell:

cmd.exe —% /c dir «C:\financial $accounts\» /w

Anything to the left of —% will be expanded:

$folder = ‘C:\financial $accounts\’
cmd.exe /c dir $folder —%/w

Inheritance

A new CMD.exe session can be instantiated in several ways, explicitly starting a new CMD session from an existing CMD shell, CALLing a batch file or implicit instantiation caused by piping a command or running a FOR /F command.

In all these cases, only the environment variable values are inherited by the new CMD session. Delayed expansion state, Command extension state and Echo state will all revert back to the default state based on the registry.
For more detail on inheritance and expansion see this StackOverflow thread.

Читайте также:  Windows new version operating system

Command Extensions

Much of the functionality of CMD.exe can be disabled — this will affect all the internal commands, and most dynamic/volatile environment variables (%TIME% , %DATE% , %RANDOM% , %CD% etc)

Command Extensions are enabled by default. This can be changed by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions
Command Extensions can also be turned on or off by running CMD /e:on or CMD /e:off
or run SETLOCAL EnableExtensions (SetLocal will take precedence)

Run a program and pass a Filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a Long Filename:
CMD /c write.exe «c:\sample documents\sample.txt»

Spaces in Program Path:
CMD /c «»c:\Program Files\Microsoft Office\Office\Winword.exe»»

Spaces in Program Path + parameters:
CMD /c «»c:\Program Files\demo.cmd»» Parameter1 Param2

Spaces in Program Path + parameters with spaces:
CMD /k «»c:\batch files\demo.cmd» «Parameter 1 with space» «Parameter2 with space»»

Launch Demo1 and then Launch Demo2:
CMD /c «»c:\Program Files\demo1.cmd» & «c:\Program Files\demo2.cmd»»

“Those who can command themselves, command others” — Hazlitt

CMD Shell — Tips on working in the Windows CMD shell.
EXIT — Use this to close a CMD shell and return.
CALL — Call one batch program from another.
START — Run a program, command or batch file.
DOSKEY — Edit command line, recall commands.
CMD Internal — Commands that are Internal to the CMD shell.
WT — Windows Terminal.
Q156276 — Cmd does not support UNC names as the current directory.
Powershell: You can run the CMD shell under Powershell, Exit will return you to the PS prompt.
Equivalent bash command (Linux): bash — run the bash shell (also csh, ksh, sh).

Использование аргументов командной строки для Терминала Windows Using command-line arguments for Windows Terminal

Вы можете использовать wt.exe для открытия нового экземпляра Терминала Windows из командной строки. You can use wt.exe to open a new instance of Windows Terminal from the command line. Кроме того, также можно использовать псевдоним выполнения wt . You can also use the execution alias wt instead.

Если вы создали Терминал Windows из исходного кода, приведенного на сайте GitHub, эту сборку можно открыть с помощью команды wtd.exe или wtd . If you built Windows Terminal from the source code on GitHub, you can open that build using wtd.exe or wtd .

Синтаксис командной строки Command line syntax

Командная строка wt принимает два типа значений: параметры и команды. The wt command line accepts two types of values: options and commands. Параметры — это список флагов и других параметров, которые могут управлять поведением командной строки wt в целом. Options are a list of flags and other parameters that can control the behavior of the wt command line as a whole. Команды представляют собой действие или список действий, разделенных точкой с запятой, которые необходимо реализовать. Commands provide the action, or list of actions separated by semicolons, that should be implemented. Если команда не указана, по умолчанию используется new-tab . If no command is specified, then the command is assumed to be new-tab by default.

Чтобы отобразить справочное сообщение со списком доступных аргументов командной строки, введите wt -h , wt —help , wt -? или wt /? . To display a help message listing the available command-line arguments, enter: wt -h , wt —help , wt -? , or wt /? .

Параметры и команды Options and commands

Ниже приведен полный список поддерживаемых команд и параметров для командной строки wt . Below is the full list of supported commands and options for the wt command line.

Параметр Option Описание Description
—help , -h , -? , /? —help , -h , -? , /? Отображает справочное сообщение. Displays the help message.
—maximized , -M —maximized , -M Запускает терминал в развернутом режиме. Launches the terminal maximized.
—fullscreen , -F —fullscreen , -F Запускает терминал в полноэкранном режиме. Launches the terminal as full screen.

—maximized , -M и —fullscreen , -F доступны только в предварительной версии Терминала Windows. —maximized , -M and —fullscreen , -F are only available in Windows Terminal Preview.

Команда Command Параметры Parameters Описание Description
new-tab —profile, -p profile-name , —startingDirectory, -d starting-directory , commandline , —title —profile, -p profile-name , —startingDirectory, -d starting-directory , commandline , —title Создает новую вкладку. Creates a new tab.
split-pane -H, —horizontal , -V, —vertical , —profile, -p profile-name , —startingDirectory, -d starting-directory , commandline , —title -H, —horizontal , -V, —vertical , —profile, -p profile-name , —startingDirectory, -d starting-directory , commandline , —title Разделяет новую панель. Splits a new pane.
focus-tab —target, -t tab-index Выделяет определенную вкладку. Focuses on a specific tab.

Примеры аргументов командной строки Command line argument examples

Команды могут различаться в зависимости от используемой командной строки. Commands may vary slightly depending on which command line you’re using.

Открыть новый экземпляр профиля Open a new profile instance

Чтобы открыть новый экземпляр терминала (в этом случае команда откроет профиль с именем Ubuntu-18.04), введите To open a new terminal instance, in this case the command will open the profile named «Ubuntu-18.04», enter:

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после выполнения. The /c option tells CMD to terminate after running.

С помощью флажка -p можно указать профиль Терминала Windows, который необходимо открыть. The -p flag is used to specify the Windows Terminal profile that should be opened. Замените Ubuntu-18.04 именем любого установленного профиля терминала. Substitute «Ubuntu-18.04» with the name of any terminal profile that you have installed. При этом всегда будет открываться новое окно. This will always open a new window. В Терминале Windows пока нельзя открывать новые вкладки или панели в имеющемся экземпляре. Windows Terminal is not yet capable of opening new tabs or panes in an existing instance.

Назначить каталог Target a directory

Чтобы указать папку, которая будет использоваться в качестве начального каталога для консоли (в данном случае каталог d:), введите: To specify the folder that should be used as the starting directory for the console, in this case the d:\ directory, enter:

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после выполнения. The /c option tells CMD to terminate after running.

Несколько вкладок Multiple tabs

Чтобы открыть новый экземпляр терминала с несколькими вкладками, введите: To open a new terminal instance with multiple tabs, enter:

В PowerShell для разделения инструкций используется точка с запятой (;). PowerShell uses a semicolon ; to delimit statements. Для интерпретации точки с запятой (;) в качестве разделителя команд для аргументов командной строки wt необходимо экранировать символы точки с запятой с помощью обратных апострофов. To interpret a semicolon ; as a command delimiter for wt command-line arguments, you need to escape semicolon characters using backticks. В PowerShell также имеется оператор прекращения анализа (—%), который дает команду остановить любую интерпретацию и выполнить передачу буквально. PowerShell also has the stop parsing operator (—%), which instructs it to stop interpreting anything after it and just pass it on verbatim.

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после выполнения. The /c option tells CMD to terminate after running.

Чтобы открыть новый экземпляр терминала с несколькими вкладками (в данном случае профиль Командной строки и профиль PowerShell), введите: To open a new terminal instance with multiple tabs, in this case a Command Prompt profile and a PowerShell profile, enter:

В PowerShell для разделения инструкций используется точка с запятой (;). PowerShell uses a semicolon ; to delimit statements. Для интерпретации точки с запятой (;) в качестве разделителя команд для аргументов командной строки wt необходимо экранировать символы точки с запятой с помощью обратных апострофов. To interpret a semicolon ; as a command delimiter for wt command-line arguments, you need to escape semicolon characters using backticks. В PowerShell также имеется оператор прекращения анализа (—%), который дает команду остановить любую интерпретацию и выполнить передачу буквально. PowerShell also has the stop parsing operator (—%), which instructs it to stop interpreting anything after it and just pass it on verbatim.

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после запуска. Сочетание косой черты и точки с запятой \; разделяет команды. The /c option tells CMD to terminate after running and the \; forward-slash + semicolon separates commands.

Несколько панелей Multiple panes

Чтобы открыть новый экземпляр терминала с одной вкладкой, содержащей три панели с профилем Командной строки, профилем PowerShell и профилем по умолчанию с командной строкой WSL, введите: To open a new terminal instance with one tab containing three panes running a Command Prompt profile, a PowerShell profile, and your default profile running a WSL command line, enter:

В PowerShell для разделения инструкций используется точка с запятой (;). PowerShell uses a semicolon ; to delimit statements. Для интерпретации точки с запятой (;) в качестве разделителя команд для аргументов командной строки wt необходимо экранировать символы точки с запятой с помощью обратных апострофов. To interpret a semicolon ; as a command delimiter for wt command-line arguments, you need to escape semicolon characters using backticks. В PowerShell также имеется оператор прекращения анализа (—%), который дает команду остановить любую интерпретацию и выполнить передачу буквально. PowerShell also has the stop parsing operator (—%), which instructs it to stop interpreting anything after it and just pass it on verbatim.

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после запуска. Сочетание косой черты и точки с запятой \; разделяет команды. The /c option tells CMD to terminate after running and the \; forward-slash + semicolon separates commands.

Флажок -H (или —horizontal ) указывает, что области должны разделяться по горизонтали. The -H flag (or —horizontal ) indicates that you would like the panes to be split horizontally. Флажок -V (или —vertical ) указывает, что панели должны разделяться по вертикали. The -V flag (or —vertical ) indicates that you would like the panes split vertically.

Заголовок вкладки (предварительная версия) Tab title (Preview)

Чтобы открыть новый экземпляр терминала с пользовательскими заголовками вкладок, используйте аргумент —title . To open a new terminal instance with custom tab titles, use the —title argument. Чтобы задать заголовок для каждой вкладки при открытии двух вкладок, введите следующее: To set the title of each tab when opening two tabs, enter:

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после запуска. Сочетание косой черты и точки с запятой \; разделяет команды. The /c option tells CMD to terminate after running and the \; forward-slash + semicolon separates commands.

Эта функция доступна только в предварительной версии Терминала Windows. This feature is only available in Windows Terminal Preview.

Фокус вкладки Tab focus

Чтобы открыть новый экземпляр терминала с определенной вкладкой в фокусе, установите флажок -t (или —target ), а также индекс вкладки. To open a new terminal instance with a specific tab in focus, use the -t flag (or —target ), along with the tab-index number. Чтобы открыть профиль по умолчанию на первой вкладке и профиль Ubuntu-18.04 в фокусе на второй вкладке ( -t 1 ), введите: To open your default profile in the first tab and the «Ubuntu-18.04» profile focused in the second tab ( -t 1 ), enter:

Псевдонимы выполнения не работают в дистрибутивах WSL. Execution aliases do not work in WSL distributions. Если вы хотите использовать wt.exe из командной строки WSL, его можно создать непосредственно из CMD, запустив cmd.exe . If you want to use wt.exe from a WSL command line, you can spawn it from CMD directly by running cmd.exe . Параметр /c указывает, что CMD должен завершить работу после запуска. Сочетание косой черты и точки с запятой \; разделяет команды. The /c option tells CMD to terminate after running and the \; forward-slash + semicolon separates commands.

Примеры нескольких команд из PowerShell Examples of multiple commands from PowerShell

В Терминале Windows используется символ точки с запятой ; в качестве разделителя команд в командной строке wt . Windows Terminal uses the semicolon character ; as a delimiter for separating commands in the wt command line. К сожалению, PowerShell также использует ; в качестве разделителя команд. Unfortunately, PowerShell also uses ; as a command separator. Чтобы решить эту проблему, воспользуйтесь следующими рекомендациями по запуску нескольких команд wt из PowerShell. To work around this, you can use the following tricks to run multiple wt commands from PowerShell. Во всех приведенных ниже примерах создается окно терминала с тремя панелями: одна с Командной строкой, вторая с PowerShell, а третья с WSL. In all the following examples, a new terminal window is created with three panes — one running Command Prompt, one with PowerShell, and the last one running WSL.

В следующих примерах для запуска wt используется команда Start-Process . The following examples use the Start-Process command to run wt . Дополнительные сведения о причинах использования Start-Process в терминале см. в разделе Использование start. For more information on why the terminal uses Start-Process , see Using start below.

Параметры с одинарными кавычками Single quoted parameters

В этом примере параметры wt заключаются в одинарные кавычки ( ‘ ). In this example, the wt parameters are wrapped in single quotes ( ‘ ). Этот синтаксис полезен при отсутствии вычислений. This syntax is useful if nothing is being calculated.

Экранированные кавычки Escaped quotes

При передаче значения, содержащегося в переменной, в командную строку wt используйте следующий синтаксис: When passing a value contained in a variable to the wt command line, use the following syntax:

Обратите внимание на использование ` для экранирования двойных кавычек ( » ) вокруг «Windows PowerShell» в параметре -p для параметра split-pane . Note the usage of ` to escape the double-quotes ( » ) around «Windows PowerShell» in the -p parameter to the split-pane parameter.

Использование start Using start

Во всех приведенных выше примерах start явно используется для запуска терминала. All the above examples explicitly used start to launch the terminal.

В следующих примерах start не используется для запуска командной строки. The following examples do not use start to run the command line. Вместо этого можно воспользоваться двумя другими методами экранирования командной строки: Instead, there are two other methods of escaping the command line:

  • Экранирование лишь точки с запятой, в результате чего PowerShell проигнорирует их и передаст непосредственно в wt . Only escaping the semicolons so that PowerShell will ignore them and pass them straight to wt .
  • Использование —% , в результате чего PowerShell будет обрабатывать оставшуюся часть командной строки как аргументы для приложения. Using —% , so PowerShell will treat the rest of the command line as arguments to the application.

В обоих примерах Терминал Windows создаст окно, правильно обработав все указанные аргументы командной строки. In both of these examples, the newly created Windows Terminal window will create the window by correctly parsing all the provided command-line arguments.

Однако в настоящее время эти методы не рекомендуемы к использованию, так как PowerShell будет ожидать закрытия созданного окна терминала перед возвратом управления в PowerShell. However, these methods are not recommended currently, as PowerShell will wait for the newly-created terminal window to be closed before returning control to PowerShell. По умолчанию PowerShell всегда ожидает закрытия приложений Магазина Windows (например, Терминала Windows) перед возвратом к командной строке. By default, PowerShell will always wait for Windows Store applications (like Windows Terminal) to close before returning to the prompt. Обратите внимание, что это поведение отличается от поведения средства «Командная строка», которое немедленно возвращается к командной строке. Note that this is different than the behavior of Command Prompt, which will return to the prompt immediately.

Читайте также:  Windows install efi boot
Оцените статью