Command alias in windows

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:

  1. 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.

  1. 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

Command alias 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 что делать

Проверено на windows 10. Спасибо за внимание!

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.

Псевдонимы в консоли 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.

Читайте также:  Установка windows с помощью uefi

Чтобы определить псевдоним консоли, используйте 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.

How to set aliases for the command prompt in Windows

In this article, I would like to share with you a useful way to define aliases for the command prompt. The method described in this article works in all modern Windows versions including Windows 10, Windows 8.1, Windows 8 and Windows 7. By following the steps below, you will be able to define any desired alias to extend the functionality of the default command processor (cmd.exe) and save your time.

Using DOSKEY, it is possible to save your time and define an alias which will allow you to omit the requirement to enter the drive letter and the /D switch. For example:

Читайте также:  Герметик акрилатный мастика windows system

The following are some special codes in Doskey macro definitions:
$T Command separator. Allows multiple commands in a macro.
$1-$9 Batch parameters. Equivalent to %1-%9 in batch programs.
$* Symbol replaced by everything following the macro name on the command line. We used it in our alias.
Now, we can compare the results without the alias and with the alias.
Without the alias, the cd command will not change the active drive:

With the alias created with DOSKEY, the command prompt will change the active drive and the current folder automatically:

This is very useful.

Using DOSKEY, it is possible to define your own aliases. For example, you can create the LS alias for the DIR command to use a common command for directory listing in Windows and Linux. As you may or may not be knowing, LS is a default file listing command in the Linux operating system.

Or something like this:

Define global aliases in the Windows command prompt

The problem with aliases is that they work only for the command prompt instance where you have defined them. To avoid this issue, you can create a new shortcut to cmd.exe or even modify the default one. You need to add the following parameters after the cmd.exe part:

Here the file c:\apps\cmd\aliases.cmd is a regular batch file which contains the appropriate DOSKEY calls.

Besides the command prompt, Windows allows defining your own aliases for the Run dialog as well. Refer to the following article: Launch your favorite apps with useful aliases from the Run dialog

That’s it. This is a very useful way to define your own command or change the behavior of default commands. I am using these aliases since a very long time. What about you? Are you using aliases in the command prompt or were you not aware of this feature?

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

Share this post

About Sergey Tkachenko

Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

6 thoughts on “ How to set aliases for the command prompt in Windows ”

A very nice effort on your part. This is really excellent documentation. I recommend it for those who tend to keep their fingers on the keyboard.

doskey router=ping -t 192.168.8.1

you can change the register instead of the parm in shotcut like this:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]
“AutoRun”=”%USERPROFILE%\\alias.cmd”

You can even store macro in specific file to load them with doskey:

echo cd=cd /D $* > test.txt
doskey /MACROFILE=test.txt
C:\Users\CodeKiller>cd C:\Windows

By the way did you know F7, ALT+F7, F8, F9 and ALT+F10 in Command-Line ? 🙂

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