Alias in windows cmd

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 10

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

Alias in windows cmd

В процессе работы web-программисту часто приходится пользоваться командной строкой. Это может быть работа с git, установка библиотек через npm или commposer. Создание шаблона приложения. Очистка кэша web-приложения. Управление миграциями базы данных и т.д.

В таком случае могут возникнуть 2 проблемы. Во-первых нужно постоянно печатать повторяющиеся команды. Либо копировать откуда-то. Во вторых нужно помнить эти самые команды. Что тоже бывает сложно. Например команда создания миграции в symfony 3 выглядит так.

В какой-то момент это все надоедает и хочется создать сокращения для команд. Под Windows можно сделать с помощью doskey.

Читайте также:  При нажатии завершение работы компьютер перезагружается windows

Alias можно создать такой командой. Однако это работает только для текущей сессии.

Если хочется создать много алиасов, имеет смысл создать .bat файл и записать туда все алиасы. Сохранить файл в удобном месте, например так:

Далее нужно сделать так, чтобы все это применялось автоматически при старте системы. Для этого нужно зайти в редактор реестра, выполнив команду regedit.

Далее найти ключ HKEY_CURRENT_USER\Software\Microsoft\Command Processor\Autorun и установить путь к .bat файлу.

Все, можно пользоваться алиасами. Мой список alias выглядит так:

Список включает в себя наиболее частоиспользуемые команды git, команды yii, symfony. Также некоторые команды для работы с mysql. Список обновляется по мере использования мною новых технологий, фреймворков и т.д.

Если нужно добавить сложную составную команду, рекомендую вынести ее в отдельный .bat файл и сделать алиас на него.

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

SukhbinderSingh.com

A self-directed apprenticeship……

Using Aliases In windows CMD

If you are like me and use mac and Linux at home and use windows at work. Then the following will be regular errors.

‘ls’ is not recognized as an internal or external command, operable program or batch file.

I always use ls, clear, cat etc. in my CMD shell and eventually get the following errors. This has happened a lot of time for me to do something about it. Fortunately, there’s an easy way to setup alias in the cmd windows and never see this nasty ‘not recognised’ error. First create a text file like this.

You can use any other commands that you use regularly. Next, open the cmd windows and type the following command

Doskey /macrofile=path/to/alias/file/filename

As shown in the next figure. That’s it.

Here’s how it works, no more nag error messages

Don’t want to type this message every time, create a windows shortcut like this

How to set an alias in Windows Command Line?

I used to work on bash and benefit a lot from alias. Is there any equivalent way in Windows Command Line?

I don’t want to simulate a Linux environment, so cygwin is not a choice. I just need some shortcut for some very long command, like cd a_very_long_path .

8 Answers 8

As Christian.K said in his comment, the DOSKEY command can be used to define macros, which are analogous to aliases.

Macro parameters are referenced in the definition via $ prefixed positions: $1 through $9 and $* for all.

See the doskey technet documentation, or type doskey /? or help doskey from the command line for more information.

But there are serious limitations with DOSKEY macros:

  • The macros only work on the interactive command line — they do not work within a batch script.
  • They cannot be used on either side of a pipe: Both someMacro|findstr ‘^’ and dir|someMacro fail.
  • They cannot be used within a FOR /F commands: for /f %A in (‘someMacro’) do . fails

The limitations are so severe that I rarely use DOSKEY macros.

Obviously you can create batch scripts instead of macros, and make sure the script locations are in your PATH. But then you must prefix each script with CALL if you want to use the script within another script.

Читайте также:  Проблемы с путями windows

You could create simple variable «macros» for long and oft used commands, but syntax is a bit awkward to type, since you need to expand the «macro» when you want to use it.

Usage (from command line or script)

You can make a batch script and save it into your path.

On Linux you would make a script and add it to the folder

/bin on windows you can do the same.

Add %USERPROFILE%\bin to your PATH environment variable. Then save your scripts in there.

Now you can type quickcd at the command line.

It can also be called inside a script using the call function

If you’re really trying to get around something like this:

You can use the subst command to map that long path to a separate drive letter

Then, when you want to jump into that folder, you can just type m: at the command line.

The advantage of this over doskey is that it works in all batch programs, and shows up in any file dialog box within Windows.

If you don’t want the mapping any more:

You could use the same trick, that windows uses: set an environment-variable (or just a variable in a batch-context) for example there is an environment-variable %windir% (and some others) So you can do an

which does the same. So all, you have to do is:

after that you can do (from whereever you are):

or whatever you want.

Unlike Linux, in Windows aliases can take arguments, and can be given parameters to assign those arguments into in their definition.

The internal built-in command is doskey, meaning it’s not an external executable file located in %SystemRoot%\System32 but is a feature of cmd.exe which itself is located in %SystemRoot% or %Windir% both pointing at C:\Windows folder by default.

Doskey defines aliases among many other things. In Windows terminology, aliases is called macros. To set an alias you use

Here $1 points to the first argument, and $* points to the all arguments.

I’d always use $* and double quote $1 if there’s only one argument to omit spaces which are treated as special characters, namely as separators (for commands).

Moreover, you can define your aliases macros in a separate file, say LinuxAliases.macro and then source it using

It will load all the aliases defined inside the file for the current session only, meaning when you exit out of cmd.exe process (also known as the shell and Command Prompt), they’re gone.

To have permanent aliases you can type the full command somewhere in a regedit key called either AutoRun or AutoCommand or something similar, what I cannot recall now alongside the macro file’s internal syntax 😛

Here are the official, and even better documentations for the command.

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