Console Aliases
This document describes console platform functionality that is no longer a part of our ecosystem roadmap. We do not recommend using this content in new products, but we will continue to support existing usages for the indefinite future. Our preferred modern solution focuses on virtual terminal sequences for maximum compatibility in cross-platform scenarios. You can find more information about this design decision in our classic console vs. virtual terminal document.
Console aliases are used to map source strings to target strings. For example, you can define a console alias that maps «test» to «cd \a_very_long_path\test». When you type «test» at the command line, the console subsystem expands the alias and executes the specified cd command.
To define a console alias, use Doskey.exe to create a macro, or use the AddConsoleAlias function. The following example uses Doskey.exe :
doskey test=cd \a_very_long_path\test
The following call to AddConsoleAlias creates the same console alias:
To add parameters to a console alias macro using Doskey.exe , use the batch parameters $1 through $9 . For more information on the special codes that can be used in Doskey macro definitions, see the command-line help for Doskey.exe or Doskey on TechNet.
All instances of an executable file running in the same console window share any defined console aliases. Multiple instances of the same executable file running in different console windows do not share console aliases. Different executable files running in the same console window do not share console aliases.
To retrieve the target string for a specified source string and executable file, use the GetConsoleAlias function. To retrieve all aliases for a specified executable file, use the GetConsoleAliases function. To retrieve the names of all aliases for which console aliases have been defined, use the GetConsoleAliasExes function.
Create command-line alias in windows
Aug 21, 2019 · 2 min read
Many time we need to use the same commands all-time in the terminal example:
- change directory to a long path like-
2. Open your server ssh terminal every time you need to run ssh commands like —
We can set an alias to quickly execute to a particular command like-
But as we close the terminal so it would not work any more. How to make it permanent.
- Create a batch file here we can write Doshkey commands
2. Copy command prompt shortcut to desktop/ any location you want —
3. Rename it to any name — alias
4. now provide a path of the batch file to this shortcut by —
a. right click on icon select properties -> shortcut
b. In target give space and add
Done. Now you can easily access your all alias by opening this shortcut
You can now put any number of alias in .bat file
Plea s e give a clap if you like this post. Also, write in the comment section.
Shivam Gupta
Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK. Love to write cool stuff
Alias commands in windows
В процессе работы web-программисту часто приходится пользоваться командной строкой. Это может быть работа с git, установка библиотек через npm или commposer. Создание шаблона приложения. Очистка кэша web-приложения. Управление миграциями базы данных и т.д.
В таком случае могут возникнуть 2 проблемы. Во-первых нужно постоянно печатать повторяющиеся команды. Либо копировать откуда-то. Во вторых нужно помнить эти самые команды. Что тоже бывает сложно. Например команда создания миграции в symfony 3 выглядит так.
В какой-то момент это все надоедает и хочется создать сокращения для команд. Под Windows можно сделать с помощью doskey.
Alias можно создать такой командой. Однако это работает только для текущей сессии.
Если хочется создать много алиасов, имеет смысл создать .bat файл и записать туда все алиасы. Сохранить файл в удобном месте, например так:
Далее нужно сделать так, чтобы все это применялось автоматически при старте системы. Для этого нужно зайти в редактор реестра, выполнив команду regedit.
Далее найти ключ HKEY_CURRENT_USER\Software\Microsoft\Command Processor\Autorun и установить путь к .bat файлу.
Все, можно пользоваться алиасами. Мой список alias выглядит так:
Список включает в себя наиболее частоиспользуемые команды git, команды yii, symfony. Также некоторые команды для работы с mysql. Список обновляется по мере использования мною новых технологий, фреймворков и т.д.
Если нужно добавить сложную составную команду, рекомендую вынести ее в отдельный .bat файл и сделать алиас на него.
Проверено на windows 10. Спасибо за внимание!
Setting Command Aliases on Windows
On Windows, aliases can be set for the Command Prompt similar to how one would set shell aliases on Linux or macOS, however, the process is slightly more complicated and requires making a change in the Windows registry.
Caution :You can modify the Windows registry by running regedit from Run in the Start Menu and then navigating to the desired key path. Be very careful when editing the registry. If you are not comfortable navigating and making changes to the registry, enlist the help of someone who is.
1. Create a folder where you want to store the file containing your alias commands- e.g. C:\Users\ \.cmds
2. In the above directory create a text file called cmds.bat
3. Edit cmds.bat with the following syntax for aliases (an example is shown below for Canopy):
5. Navigate to HKEY_CURRENT_USER => Software => Microsoft => Command Processor
6. Add a String valued entry with the name AutoRun. For the value, enter the full path to the cmds.bat file your created — e.g. C:\Users\ \.cmds\cmds.bat
7. From now on, aliases defined in cmds.bat will be available to your Command Prompt sessions.
Example of useful aliases for Enthought Canopy (assuming standard installation):
Using the aliases above, if you’d like to open a Canopy command prompt you can execute:
If you’d like to start the Canopy GUI from the command line you can execute:
Псевдонимы в консоли Console Aliases
В этом документе описываются функциональные возможности платформы консоли, которые больше не являются частью нашего плана экосистемы . This document describes console platform functionality that is no longer a part of our ecosystem roadmap . Мы не советуем использовать это содержимое в новых продуктах, но мы будем продолжать поддерживать существующие случаи использования в течение неопределенного будущего. We do not recommend using this content in new products, but we will continue to support existing usages for the indefinite future. Наше рекомендуемое современное решение посвящено виртуальным последовательностью терминалов для обеспечения максимальной совместимости в межплатформенных сценариях. Our preferred modern solution focuses on virtual terminal sequences for maximum compatibility in cross-platform scenarios. Дополнительные сведения об этом решении по проектированию можно найти в классической консоли и в виртуальном документе терминала . You can find more information about this design decision in our classic console vs. virtual terminal document.
Псевдонимы консоли используются для отображения исходных строк в целевых строках. Console aliases are used to map source strings to target strings. Например, можно определить псевдоним консоли, который сопоставляет «Test» с «CD \ — _ очень _ длинная _ Проверка пути \ «. For example, you can define a console alias that maps «test» to «cd \a_very_long_path\test». При вводе в командной строке команды «Test» подсистема консоли расширяет псевдоним и выполняет указанную команду CD. When you type «test» at the command line, the console subsystem expands the alias and executes the specified cd command.
Чтобы определить псевдоним консоли, используйте Doskey.exe для создания макроса или используйте функцию аддконсолеалиас . To define a console alias, use Doskey.exe to create a macro, or use the AddConsoleAlias function. В следующем примере используется Doskey.exe . The following example uses Doskey.exe :
Doskey Test = CD \ \ Проверка _ очень _ длинного _ пути doskey test=cd \a_very_long_path\test
Следующий вызов аддконсолеалиас создает тот же псевдоним консоли: The following call to AddConsoleAlias creates the same console alias:
Чтобы добавить параметры в макрос псевдонима консоли с помощью Doskey.exe , используйте параметры пакетной службы с помощью команды $1 $9 . To add parameters to a console alias macro using Doskey.exe , use the batch parameters $1 through $9 . Дополнительные сведения о специальных кодах, которые можно использовать в определениях макросов doskey, см. в справке командной строки для Doskey.exe или Doskey на сайте TechNet. For more information on the special codes that can be used in Doskey macro definitions, see the command-line help for Doskey.exe or Doskey on TechNet.
Все экземпляры исполняемого файла, работающего в том же окне консоли, имеют все определенные псевдонимы консоли. All instances of an executable file running in the same console window share any defined console aliases. Несколько экземпляров одного и того же исполняемого файла, работающего в разных окнах консоли, не имеют общих псевдонимов консоли. Multiple instances of the same executable file running in different console windows do not share console aliases. Разные исполняемые файлы, работающие в одном окне консоли, не имеют общих псевдонимов консоли. Different executable files running in the same console window do not share console aliases.
Чтобы получить целевую строку для указанной исходной строки и исполняемого файла, используйте функцию жетконсолеалиас . To retrieve the target string for a specified source string and executable file, use the GetConsoleAlias function. Чтобы получить все псевдонимы для указанного исполняемого файла, используйте функцию жетконсолеалиасес . To retrieve all aliases for a specified executable file, use the GetConsoleAliases function. Чтобы получить имена всех псевдонимов, для которых были определены псевдонимы консоли, используйте функцию жетконсолеалиасексес . To retrieve the names of all aliases for which console aliases have been defined, use the GetConsoleAliasExes function.