Windows command line string commands

Command prompt (Cmd. exe) command-line string limitation

This article discusses the limitation to the length of the strings that you use from the command prompt in Command Prompt (Cmd.exe). It also provides methods that you can use to work around this limitation.

Original product version: В Windows Server 2012 R2, Windows Server 2008 R2 Service Pack 1, Windows 7 Service Pack 1
Original KB number: В 830473

More information

The maximum length of the string that you can use at the command prompt is 8191 characters.

This limitation applies to:

  • the command line
  • individual environment variables that are inherited by other processes, such as the PATH variable
  • all environment variable expansions

If you use Command Prompt to run batch files, this limitation also applies to batch file processing.

Examples

The following examples show how this limitation applies to commands that you run in Command Prompt, and commands that you use in a batch file.

In Command Prompt, the total length of the following command line can’t contain more than 8191 characters:

In a batch file, the total length of the following command line can’t contain more than 8191 characters:

This limitation applies to command lines that are contained in batch files when you use Command Prompt to run the batch file.

In Command Prompt, the total length of EnvironmentVariable1 after you expand EnvironmentVariable2 and EnvironmentVariable3 can’t contain more than 8191 characters:

In a batch file, the total length of the following command line after you expand the parameters can’t contain more than 8191 characters:

Even though the Win32 limitation for environment variables is 32,767 characters, Command Prompt ignores any environment variables that are inherited from the parent process and are longer than its own limitations of 8191 characters (as appropriate to the operating system). For more information about the SetEnvironmentVariable function, see SetEnvironmentVariableA function.

How to work around the limitation

To work around the limitation, use one or more of the following methods, as appropriate to your situation:

Modify programs that require long command lines so that they use a file that contains the parameter information, and then include the name of the file in the command line.

For example, instead of using the ExecutableFile.exe Parameter1 Parameter2. ParameterN command line in a batch file, modify the program to use a command line that is similar to the following command line, where ParameterFile is a file that contains the required parameters (parameter1 parameter2. ParameterN):

Modify programs that use large environment variables so that the environment variables contain less than 8191 characters.

For example, if the PATH environment variable contains more than 8191 characters, use one or more of the following methods to reduce the number of characters:

  • Use shorter names for folders and files.
  • Reduce the depth of folder trees.
  • Store files in fewer folders so that fewer folders are required in the PATH environment variable.
  • Investigate possible methods that you can use to reduce the dependency of PATH for locating .dll files.
Читайте также:  Обновитесь до windows 10 как удалить

—>

Командные строки

Чтобы отправить командную строку на устройство MCI, используйте функцию mciSendString , которая включает параметры для команды String и буфер для любых возвращаемых сведений.

Функция mciSendString возвращает нуль в случае успеха. Если функция завершается ошибкой, в слове с низким порядком возвращаемого значения содержится код ошибки. Этот код ошибки можно передать функции мЦижетеррорстринг , чтобы получить текстовое описание ошибки.

Синтаксис командных строк

В строках команд MCI используется единообразный синтаксис модификатора глагола-Object. Каждая Командная строка содержит команду, идентификатор устройства и аргументы команды. Аргументы являются необязательными для некоторых команд и являются обязательными для других.

Командная строка имеет следующий вид:

аргументы идентификатора устройства командной строки _

Эти компоненты содержат следующие сведения:

_ Идентификатор устройства определяет экземпляр драйвера MCI. _ Идентификатор устройства создается при открытии устройства.

Аргументы задают флаги и переменные, используемые командой. Флаги — это ключевые слова, распознаваемые командой MCI. Переменные — это числа или строки, которые применяются к команде или флагу MCI.

Например, команда Play использует аргументы «от позиции » и «to position » для указания позиций, с которых начинается и заканчивается воспроизведение. Вы можете перечислить флаги, используемые командой, в любом порядке. При использовании флага, связанного с переменной, необходимо указать значение для переменной.

Неуказанные (и необязательные) аргументы команды предполагают значение по умолчанию.

Следующий пример функции отправляет команду Play с флагами «from» и «to».

Типы данных для переменных команд

В командной строке можно использовать следующие типы данных для переменных.

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.

Читайте также:  Mac os leopard books

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.

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.

How to write a multiline command?

How do we extend a command to the next line?

Basically whats the windows alternative for Linux’s

Here we use backslashes to extend the command onto the next lines.

What’s the equivalent for Windows?

4 Answers 4

After trying almost every key on my keyboard:

So it seems to be the ^ key.

In the Windows Command Prompt the ^ is used to escape the next character on the command line. (Like \ is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that’s why it works for the newline.

For reference the characters that need escaping (if specified as command arguments and not within quotes) are: &|()

So the equivalent of your linux example would be (the More? being a prompt):

The caret character works, however the next line should not start with double quotes. e.g. this will not work:

Start next line without double quotes (not a valid example, just to illustrate)

If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.

Trying to use this with things that actually use piping, like say findstr is quite problematic. The same goes for dealing with else s. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.

Let’s say you have something like this in a batch that you want to run directly in command prompt:

Now, you could use the line-continuation carat ( ^ ) and manually type it out like this, but warning, it’s tedious and if you mess up you can learn the joy of typing it all out again.

Читайте также:  Hard disk low level format tool windows 10

Well, it won’t work with just ^ thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:

Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don’t need no carats by swapping them out for a single pipe ( | ) per continuation of a loop/expression:

How do I run two commands in one line in Windows CMD?

I want to run two commands in a Windows CMD console.

In Linux I would do it like this

How is it done on Windows?

21 Answers 21

Like this on all Microsoft OSes since 2000, and still good today:

If you want the second command to execute only if the first exited successfully:

The single ampersand (&) syntax to execute multiple commands on one line goes back to Windows XP, Windows 2000, and some earlier NT versions. (4.0 at least, according to one commenter here.)

There are quite a few other points about this that you’ll find scrolling down this page.

Historical data follows, for those who may find it educational.

Prior to that, the && syntax was only a feature of the shell replacement 4DOS before that feature was added to the Microsoft command interpreter.

In Windows 95, 98 and ME, you’d use the pipe character instead:

In MS-DOS 5.0 and later, through some earlier Windows and NT versions of the command interpreter, the (undocumented) command separator was character 20 (Ctrl+T) which I’ll represent with ^T here.

A quote from the documentation:

Using multiple commands and conditional processing symbols

You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.

For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.

You can use the special characters listed in the following table to pass multiple commands.

& [. ]
command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

&& [. ]
command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.

|| [. ]
command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).

( ) [. ]
(command1 & command2)
Use to group or nest multiple commands.

; or ,
command1 parameter1;parameter2
Use to separate command parameters.

Оцените статью