Visual studio cmd windows

Командная строка разработчика и PowerShell для разработчиков в Visual Studio Visual Studio Developer Command Prompt and Developer PowerShell

В Visual Studio 2019 есть две оболочки командной строки для разработчиков: Visual Studio 2019 includes two command-line shells for developers:

Командная строка разработчика для Visual Studio — стандартная командная строка с определенными переменными среды, упрощающая работу с инструментами разработки. Visual Studio Developer Command Prompt — A standard command prompt with certain environment variables set to make using command-line developer tools easier. Доступно с версии Visual Studio 2015. Available since Visual Studio 2015.

PowerShell для разработчиков Visual Studio — более функциональное средство, чем командная строка. Visual Studio Developer PowerShell — More powerful than a command prompt. Например, в нем можно передать результат одной команды (называемой cmdlet ) в другой cmdlet. For example, you can pass the output of one command (known as a cmdlet) to another cmdlet. В этой оболочке доступны те же переменные среды, что и в Командной строке разработчика. This shell has the same environment variables set as Developer Command Prompt. Доступно с версии Visual Studio 2019. Available since Visual Studio 2019.

Начиная с версии 16.5, в Visual Studio 2019 доступен встроенный терминал, где можно работать как с Командной строкой разработчика, так и с PowerShell для разработчиков. Starting in Visual Studio 2019 version 16.5, Visual Studio includes an integrated terminal that can host either of these shells (Developer Command Prompt and Developer PowerShell). Можно открыть несколько вкладок для каждой оболочки. You can also open multiple tabs of each shell. Терминал Visual Studio построен на основе Терминала Windows. The Visual Studio terminal is built on top of Windows Terminal. Чтобы открыть терминал в Visual Studio, выберите элементы Вид > Терминал. To open the terminal in Visual Studio, choose View > Terminal.

При запуске в Visual Studio одной из оболочек как отдельного приложения или в окне терминала открывается каталог текущего решения (если оно загружено). When you open one of the developer shells from Visual Studio, either as a separate app or in the Terminal window, it opens to the directory of your current solution (if you have a solution loaded). Это упрощает выполнение команд для решения или его проектов. This behavior makes it convenient to run commands against the solution or its projects.

В обеих оболочках заданы определенные переменные среды. Это упрощает работу с инструментами командной строки. Both shells have specific environment variables set that enable you to use command-line developer tools more easily. Открыв эти оболочки, можно выполнять команды для различных служебных программ, не указывая их расположения. After opening one of these shells, you can enter the commands for different utilities without having to know where they’re located.

Популярные команды Popular commands Описание Description
MSBuild Сборка проекта или решения Build a project or solution
clrver Инструменты .NET Framework для CLR. A .NET Framework tools for clr.
ildasm Инструменты .NET Framework для дизассемблера. A .NET Framework tool for disassembler.
dotnet Команда CLI .NET A .NET CLI command
dotnet run Команда CLI .NET A .NET CLI command
CL Средство компиляции C/C++ C/C++ compile tool
NMAKE Средство компиляции C/C++ C/C++ compile tool
LIB Средство сборки С/C++ C/C++ build tool
DUMPBIN Средство сборки С/C++ C/C++ build tool

Запуск в Visual Studio Start in Visual Studio

Выполните следующие действия, чтобы открыть в Visual Studio Командную строку разработчика или PowerShell для разработчиков: Follow these steps to open Developer Command Prompt or Developer PowerShell from within Visual Studio:

Запустите Visual Studio. Open Visual Studio.

В строке меню выберите элементы Инструменты > Командная строка > Командная строка разработчика или PowerShell для разработчиков. On the menu bar, choose Tools > Command Line > Developer Command Prompt or Developer PowerShell.

Запуск из меню Windows Start from Windows menu

Другой способ запуска оболочек — из меню «Пуск». Another way to start the shells is from the Start menu. В зависимости от версии Visual Studio, дополнительно установленных пакетов SDK и рабочих нагрузок может иметься несколько вариантов командных строк. You may have multiple command prompts, depending on the version of Visual Studio and any additional SDKs and workloads you’ve installed.

Windows 10 Windows 10

Выберите Пуск Select Start и прокрутите до буквы V. and scroll to the letter V.

Разверните папку Visual Studio 2019. Expand the Visual Studio 2019 folder.

Выберите вариант Developer Command Prompt for VS 2019 (Командная строка разработчика для VS 2019) или Developer PowerShell for VS 2019 (PowerShell для разработчиков для VS 2019). Choose Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.

Кроме того, вы можете начать вводить имя оболочки в поле поиска на панели задач и выбрать нужный результат, так как в списке результатов начнут отображаться найденные совпадения. Alternatively, you can start typing the name of the shell in the search box on the taskbar, and choose the result you want as the result list starts to display the search matches.

Windows 8.1 Windows 8.1

Перейдите на экран Пуск, нажав клавишу с логотипом Windows Go to the Start screen, by pressing the Windows logo key на клавиатуре, например. on your keyboard for example.

На начальном экране нажмите Ctrl+Tab, чтобы открыть список приложений, а затем нажмите V. Появится список, включающий все установленные командные строки Visual Studio. On the Start screen, press Ctrl+Tab to open the Apps list, and then press V. This brings up a list that includes all installed Visual Studio command prompts.

Выберите вариант Developer Command Prompt for VS 2019 (Командная строка разработчика для VS 2019) или Developer PowerShell for VS 2019 (PowerShell для разработчиков для VS 2019). Choose Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.

Windows 7 Windows 7

Выберите Пуск а затем разверните Все программы. Choose Start and then expand All Programs.

Выберите элементы Visual Studio 2019 > Инструменты Visual Studio > Developer Command Prompt for VS 2019 (Командная строка разработчика для VS 2019) или Developer PowerShell for VS 2019 (PowerShell для разработчиков для VS 2019) . Choose Visual Studio 2019 > Visual Studio Tools > Developer Command Prompt for VS 2019 or Developer PowerShell for VS 2019.

Если установлены другие пакеты SDK, например, пакет SDK для Windows 10 или предыдущих версий, могут появиться дополнительные командные строки. If you have other SDKs installed, such as the Windows 10 SDK or previous versions, you may see additional command prompts. Требуемая версия командной строки указана в документации по соответствующим инструментам. Check the documentation for the individual tools to determine which version of the command prompt you should use.

Запуск из обозревателя файлов Start from file browser

Обычно ярлыки для установленных оболочек помещаются в папку меню «Пуск» для Visual Studio, например в %ProgramData%\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools. Usually, the shortcuts for the shells you have installed are placed in the Start Menu folder for Visual Studio, such as in %ProgramData%\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools. Но если поиск командной строки не дает ожидаемых результатов, попробуйте вручную найти нужные файлы на компьютере. But if searching for the command prompt doesn’t produce the expected results, you can try to manually locate the files on your machine.

Командная строка разработчика Developer Command Prompt

Выполните поиск файла командной строки (VsDevCmd.bat) или перейдите в папку «Инструменты» Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools — путь зависит от версии Visual Studio, выпуска и расположения установки). Search for the name of the command prompt file, which is VsDevCmd.bat, or go to the Tools folder for Visual Studio, such as %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools (path changes according to your Visual Studio version, edition, and installation location).

Когда вы найдете файл командной строки, откройте его. Для этого введите следующую команду в стандартном окне командной строки: Once you’ve located the command prompt file, open it by entering the following command in a regular command prompt window:

Кроме того, вы можете ввести следующую команду в диалоговом окне Windows Выполнить: Or enter the following command in the Windows Run dialog box:

Вам необходимо изменить путь в соответствии с расположением установки Visual Studio. You’ll need to edit the path to match your Visual Studio installation.

PowerShell для разработчиков Developer PowerShell

Найдите файл скрипта PowerShell с именем Launch-VsDevShell.ps1 или перейдите в папку «Инструменты» Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools). Search for a PowerShell script file named Launch-VsDevShell.ps1, or go to the Tools folder for Visual Studio, such as %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools. Путь зависит от версии, выпуска и расположения установки Visual Studio. После этого выполните следующую команду в командной строке Windows PowerShell или PowerShell 6: (The path changes according to your Visual Studio version, edition, and installation location.) Once you’ve located the PowerShell file, run it by entering the following command at a Windows PowerShell or PowerShell 6 prompt:

По умолчанию PowerShell для разработчиков запускается с конфигурацией для той версии Visual Studio, путь установки к которой указан в файле Launch-VsDevShell.ps1. By default, the Developer PowerShell that launches is configured for the Visual Studio installation whose install path the Launch-VsDevShell.ps1 file is located in.

Чтобы выполнить cmdlet, нужно задать политику выполнения. The execution policy must be set in order for the cmdlet to run.

Окно команд Command Window

Командное окно используется для выполнения команд или их псевдонимов непосредственно в интегрированной среде разработки (IDE) Visual Studio Visual Studio . The Command window is used to execute commands or aliases directly in the Visual Studio Visual Studio integrated development environment (IDE). Можно выполнять команды меню и команды, которые не отображаются в меню. You can execute both menu commands and commands that do not appear on any menu. Для вывода командного окна в меню Вид выберите Другие окна, а затем Командное окно. To display the Command window, choose Other Windows from the View menu, and select Command Window.

Отображение значений переменных Displaying the Values of Variables

Для проверки значения переменной varA используйте команду Print: To check the value of a variable varA , use the Print Command:

Вопросительный знак (?) является псевдонимом для команды Debug.Print , поэтому можно также написать такую команду: The question mark (?) is an alias for Debug.Print , so this command can also be written:

Обе версии этой команды возвращают значение переменной varA . Both versions of this command will return the value of the variable varA .

Ввод команд Entering Commands

Символ «больше чем» ( > ) отображается в левой части окна командной строки для запроса новых строк. The greater than symbol ( > ) appears at the left edge of the Command window as a prompt for new lines. Используйте клавиши со стрелками ВВЕРХ и ВНИЗ для прокрутки ранее выполненных команд. Use the UP ARROW and DOWN ARROW keys to scroll through previously issued commands.

Задача Task Решение Solution Пример Example
Вычисление выражения Evaluate an expression. Установите перед выражением знак вопроса ( ? ). Preface the expression with a question mark ( ? ). ? myvar
Переключение в окно интерпретации Switch to an Immediate window. Введите в окне immed без знака «больше чем» (>). Enter immed into the window without the greater than sign (>) immed
Возврат в командное окно из окна интерпретации Switch back to the Command window from an Immediate window. Введите в окне cmd . Enter cmd into the window. >cmd

Следующие сочетания клавиш помогают выполнять переходы в режиме команд. The following shortcuts help you navigate while in Command mode.

Действие Action Положение курсора Cursor location Настраиваемое сочетание клавиш Keybinding
Пролистать список ранее введенных команд Cycle through the list of previously entered commands. Строка ввода Input line СТРЕЛКА ВВЕРХ и СТРЕЛКА ВНИЗ UP ARROW & DOWN ARROW
Прокрутка окна вверх Scroll up the window. Содержимое командного окна Command window contents CTRL+СТРЕЛКА ВВЕРХ CTRL+UP ARROW
Прокрутка окна вниз Scroll down the window. Содержимое командного окна Command window contents СТРЕЛКА ВНИЗ или CTRL + СТРЕЛКА ВНИЗ DOWN ARROW or CTRL+DOWN ARROW

Всю предыдущую команду или ее часть можно скопировать в строку ввода: перейдите к команде с помощью прокрутки, выделите всю команду или ее часть и нажмите клавишу ВВОД. You can copy all or part of a previous command to the input line by scrolling to it, highlighting all or part of it, and then pressing ENTER.

Режим пометки Mark Mode

При щелчке любой предыдущей строки в командном окне происходит автоматическое переключение в режим пометки. When you click on any previous line in the Command window, you shift automatically into Mark mode. Он позволяет выбирать, изменять и копировать текст предыдущих команд как в любом текстовом редакторе и вставлять их в текущую строку. This allows you to select, edit, and copy the text of previous commands as you would in any text editor, and paste them into the current line.

Знак равенства (=) The Equals (=) Sign

Окно, используемое для ввода команды EvaluateStatement , определяет, интерпретируется ли знак равенства (=) как оператор сравнения или оператор присваивания. The window used to enter the EvaluateStatement command determines whether an equals sign (=) is interpreted as a comparison operator or as an assignment operator.

В командном окне знак равенства (=) интерпретируется как оператор сравнения. In the Command window, an equals sign (=) is interpreted as a comparison operator. Операторы присваивания нельзя использовать в командном окне. You cannot use assignment operators in the Command window. Например, если значения переменных varA и varB различаются, то команда >Debug.EvaluateStatement(varA=varB) вернет значение False . So, for example, if the values of variables varA and varB are different, then the command >Debug.EvaluateStatement(varA=varB) will return a value of False .

В окне интерпретации, напротив, знак равенства (=) интерпретируется как оператор присваивания. In the Immediate window, by contrast, an equals sign (=) is interpreted as an assignment operator. Например, команда >Debug.EvaluateStatement(varA=varB) присвоит переменной varA значение переменной varB . So, for example, the command >Debug.EvaluateStatement(varA=varB) will assign to variable varA the value of variable varB .

Параметры, аргументы и значения Parameters, Switches, and Values

Некоторые команды Visual Studio Visual Studio имеют обязательные и необязательные аргументы, параметры и значения. Some Visual Studio Visual Studio commands have required and optional arguments, switches and values. При работе с такими командами применяются определенные правила. Certain rules apply when dealing with such commands. Ниже приведен пример расширенной команды для пояснения используемой терминологии. The following is an example of a rich command to clarify the terminology.

В этом примере In this example,

Edit.ReplaceInFiles — это команда; Edit.ReplaceInFiles is the command

/case и /pattern:regex — это параметры командной строки (начинаются с символа косой черты [/]); /case and /pattern:regex are switches (prefaced with the slash [/] character)

regex — это значение параметра командной строки /pattern (параметр /case не имеет значения); regex is the value of the /pattern switch; the /case switch has no value

var3+ и oldpar — это параметры. var2+ and oldpar are parameters

Команду, параметр или значение, содержащее пробелы, необходимо заключить в кавычки. Any command, parameter, switch, or value that contains spaces must have double quotation marks on either side.

Положение параметров в командной строке может быть произвольным, за исключением команды Shell, в которой параметры должны следовать в определенном порядке. The position of switches and parameters can be interchanged freely on the command line with the exception of the Shell command, which requires its switches and parameters in a specific order.

Почти все параметры, поддерживаемые командой, имеют две формы: краткую (один символ) и длинную. Nearly every switch supported by a command has two forms: a short (one character) form and a long form. Несколько параметров в краткой форме можно объединять в группы. Multiple short-form switches can be combined into a group. Например, значение /p /g /m можно также представить как /pgm . For example, /p /g /m can be expressed alternately as /pgm .

Если параметры в краткой форме будут объединены в группу, и ей будет присвоено значение, это значение присваивается каждому параметру. If short-form switches are combined into a group and given a value, that value applies to every switch. Например, /pgm:123 соответствует /p:123 /g:123 /m:123 . For example, /pgm:123 equates to /p:123 /g:123 /m:123 . Если какой-либо из параметров в группе не принимает значение, возникает ошибка. An error occurs if any of the switches in the group does not accept a value.

Escape-символы Escape Characters

Символ «крышки» (^) в командной строке означает, что следующий за ним символ интерпретируется буквально, а не как управляющий символ. A caret (^) character in a command line means that the character immediately following it is interpreted literally, rather than as a control character. Благодаря этому в значение параметра можно внедрить прямые кавычки («), пробелы, начальные символы косой черты, крышки или другие знаки, за исключением имен параметров. This can be used to embed straight quotation marks («), spaces, leading slashes, carets, or any other literal characters in a parameter or switch value, with the exception of switch names. Например, For example,

Крышка действует одинаково как внутри кавычек, так и за их пределами. A caret functions the same whether it is inside or outside quotation marks. Если крышка является последним символом в строке, она игнорируется. If a caret is the last character on the line, it is ignored. В следующем примере показано, как выполнить поиск шаблона «^t». The example shown here demonstrates how to search for the pattern «^t».

Использование кавычек для путей с пробелами Use Quotes for Path Names with Spaces

Например, если вы хотите открыть файл, путь к которому содержит пробелы, необходимо заключить путь или сегмент пути, содержащий пробелы, в двойные кавычки: C:\»Program Files» или «C:\Program Files». If, for example, you want to open a file that has a path containing spaces, you must put double quotes around the path or path segment that contains spaces: C:\»Program Files» or «C:\Program Files».

Читайте также:  Создание загрузочной флешки для mac os catalina
Оцените статью