519

I have added notepad++.exe to my Path in environment variables.

Now in command prompt, notepad++.exe filename.txt opens the filename.txt. But I want to do just np filename.txt to open the file.

I tried using DOSKEY np=notepad++. But it is just bringing to the forefront an already opened Notepad++ without opening the file. How can I make it open the file?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Romonov
  • 8,145
  • 14
  • 43
  • 55

20 Answers20

603

To add to josh's answer,

you may make the alias(es) persistent with the following steps,

  1. Create a .bat or .cmd file with your DOSKEY commands.

  2. Run regedit and go to HKEY_CURRENT_USER\Software\Microsoft\Command Processor

  3. Add String Value entry with the name AutoRun and the full path of your .bat/.cmd file.

    For example, %USERPROFILE%\alias.cmd, replacing the initial segment of the path with %USERPROFILE% is useful for syncing among multiple machines.

This way, every time cmd is run, the aliases are loaded.

For Windows 10 or Windows 11, add the entry to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor instead.

(For Windows 11, also note that by default the "Terminal App" points to PowerShell. Search "cmd" for command prompt.)

For completeness, here is a template to illustrate the kind of aliases one may find useful.

@echo off

:: Temporary system path at cmd startup

set PATH=%PATH%;"C:\Program Files\Sublime Text 2\"

:: Add to path by command

DOSKEY add_python26=set PATH=%PATH%;"C:\Python26\"
DOSKEY add_python33=set PATH=%PATH%;"C:\Python33\"

:: Commands

DOSKEY ls=dir /B $*
DOSKEY sublime=sublime_text $*  
    ::sublime_text.exe is name of the executable. By adding a temporary entry to system path, we don't have to write the whole directory anymore.
DOSKEY gsp="C:\Program Files (x86)\Sketchpad5\GSP505en.exe"
DOSKEY alias=notepad %USERPROFILE%\Dropbox\alias.cmd

:: Common directories

DOSKEY dropbox=cd "%USERPROFILE%\Dropbox\$*"
DOSKEY research=cd %USERPROFILE%\Dropbox\Research\

  • Note that the $* syntax works after a directory string as well as an executable which takes in arguments. So in the above example, the user-defined command dropbox research points to the same directory as research.
  • As Rivenfall pointed out, it is a good idea to include a command that allows for convenient editing of the alias.cmd file. See alias above. If you are in a cmd session, enter cmd to restart cmd and reload the alias.cmd file.

When I searched the internet for an answer to the question, somehow the discussions were either focused on persistence only or on some usage of DOSKEY only. I hope someone will benefit from these two aspects being together here!


Here's a .reg file to help you install the alias.cmd. It's set now as an example to a dropbox folder as suggested above.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"AutoRun"="%USERPROFILE%\\alias.cmd"

For single-user applications, the above will do. Nevertheless, there are situations where it is necessary to check whether alias.cmd exists first in the registry key. See example below.

In a C:\Users\Public\init.cmd file hosting potentially cross-user configurations:

@ECHO OFF
REM Add other configurations as needed
IF EXIST "%USERPROFILE%\alias.cmd" ( CALL "%USERPROFILE%\alias.cmd" )

The registry key should be updated correspondly to C:\Users\Public\init.cmd or, using the .reg file:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"AutoRun"="C:\\Users\\Public\\init.cmd"
Argyll
  • 8,591
  • 4
  • 25
  • 46
  • 4
    exactly what I needed; works perfectly; I recommend adding a doskey to actually edit the env.cmd file – Rivenfall Jan 07 '15 at 14:09
  • 12
    This is naive and inefficient. The autorun batch file will be run for every instance of cmd.exe, including the `system` function. It needs to exit if a certain variable (e.g. `AUTORUN`) is defined. Otherwise set up the environment (`set AUTORUN=1`) and set up doskey in a single pass using the macrofile option instead of running doskey.exe to define each alias. – Eryk Sun Aug 02 '15 at 09:27
  • @Argyll thanks for your answer, However every time I open a cmd window , all of my DOSKEY commands are printed on the windows. Is there a way to run it on the background. – H'H Dec 19 '16 at 15:17
  • 1
    I think the `@echo off` command should be able to turn the printing off. – Argyll Dec 21 '16 at 03:37
  • 4
    @eryksun can you post or link to a less naive example? I know how to exit if autorun is defined, but confused over how to set or unset it in the first place without having already run CMD. – matt wilkie Sep 06 '17 at 18:23
  • using .cmd did not work for me, although using .bat did – Chris Dec 05 '18 at 10:58
  • If you don't want to deal with editing register values, press `Start`, type `cmd`, right click `cmd` and open the location, right click `cmd.exe` and open properties, then add `/k path_to_bat_file.bat`. – okovko Jan 13 '19 at 11:50
  • 8
    What's the replacement for `HKEY_CURRENT_USER\Software\Microsoft\Command Processor` in the present day? I can't seem to find that path in regedit anymore – Jan Apr 13 '19 at 22:10
  • @Jan: I don't have Win 10 to find out. Search up on command prompt in win 10? I remember cmd being a limited version in win 10 from my brief encounters with them. – Argyll Apr 17 '19 at 17:04
  • @Argyll Guess I could've googled it first -- This article looks promising: https://www.nucleustechnologies.com/blog/three-methods-to-disable-autorun-in-windows-10/ Not by my Windows 10 machine atm but I'll check back here when I get a chance to try it out. – Jan Apr 18 '19 at 16:09
  • @Jan: good luck. Let me know if you find anything. Increasingly more people may need it now that Win 7 is going to stop receiving updates. – Argyll Apr 19 '19 at 17:03
  • @Jan did you manage to find anything in that article that worked? I still wasn't able to find an equivalent. – jnotelddim Aug 08 '19 at 18:28
  • 3
    @Jan For me, it was in `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor`. I used the Edit->Find functionality in the Registry Editor to find it. – erwaman Sep 06 '19 at 21:12
  • 2
    I just got a new computer with win 10. `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor` works for me. – Argyll Sep 30 '19 at 21:11
  • 5
    I like this. A similar option is to put in the autorun: `doskey /macrofile="%USERPROFILE%\alias"`. And next put the aliases in the 'alias' file, without the 'doskey' part. A solution an admin could use to restrict autorun definitions to aliases a user could self-make. Preventing users from autorunning other stuff. – user1708042 Oct 07 '19 at 12:50
  • 3
    Please note that this solution may cause problems down the line (I have had build with automated tools strangely fail for seemingly no reason at all). It may be best to have a globally accessible `bat` file with calls the `%USERPROFILE%\alias.cmd` only if defined. For instance... `IF EXIST "%USERPROFILE%\alias.cmd" ( CALL "%USERPROFILE%\alias.cmd")` This should prevent "leakage" of non-existing configuration errors in subcommand prompts (node, maven, ...) – Markio May 14 '20 at 06:42
  • @Markio: Good point. Would you like to edit it into the answer? (Only after verifying the code ofc.) – Argyll May 17 '20 at 11:11
  • @Markio: An edit does need to integrate into the answer in style as well. So you see, phrases starting with "I would instead..." wouldn't make sense when others read the edited answer. So I am going to approve the edit. But as well, I'll make the style changes to your edit. (Hopefully other reviewers see my reasoning here. After all, **I did not check that the new files work**, which I otherwise should do before approving edits.) Thank you for your contribution in any case! – Argyll May 25 '20 at 19:08
  • 1
    @Jan: You can create a "Command Processor" key by hand under HKCU\Software\Microsoft (with the Autorun string value in it). Works well for me under Win10. – Cameron Mar 30 '21 at 17:40
  • 1
    Nice works. If you want to switch jdk, maybe you can add something like this.`DOSKEY setjdk8=set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_301$tset PATH=C:\Program Files\Java\jdk1.8.0_301\bin;%PATH%; DOSKEY setjdk17=set JAVA_HOME=C:\Program Files\Java\jdk-17$tset PATH=C:\Program Files\Java\jdk-17\bin;%PATH%;` Be care of `$t`, not around spaces allowed here. – Donghua Liu Oct 19 '21 at 12:31
  • I don't recommend using the registry option at all, as it can have many undesired consequences and affect other programs, specially if current directory is changed, as explained here: https://devblogs.microsoft.com/oldnewthing/20071121-00/?p=24433. It's better to edit the command prompt shortcut (or duplicate it) to run a script at start with /k. – Aníbal Mar 01 '22 at 17:43
  • I recommend `DOSKEY ls=dir /B "$*"` – imjosh May 04 '22 at 19:14
  • @imjosh: forgive my laziness to look/try things up/out. Why `""`? – Argyll May 05 '22 at 18:17
  • @Argyll "$*" let's you pass a path from the alias to the command. So `ls .\path\to\directory` will work. I think the `""` are required so doskey knows it's not a literal string. – imjosh May 06 '22 at 21:08
  • 1
    @imjosh: the use case makes sense. I edited accordingly. Didn't include `""`. Wrapping input with `""` is something the user can (also) do. Though it may be interesting to double-check how cmd unwraps layers of `""`. – Argyll May 09 '22 at 19:57
  • Maybe update to something similar "For Windows 11 and 10, add the entry to..." ? Now I thought the first file path was for Windows 11 as I didn't check the publish date at first. Thank you. – Anna Madsen Dec 06 '22 at 08:45
286

You need to pass the parameters, try this:

doskey np=notepad++.exe $*

Edit (responding to Romonov's comment) Q: Is there any way I can make the command prompt remember so I don't have to run this each time I open a new command prompt?

doskey is a textual command that is interpreted by the command processor (e.g. cmd.exe), it can't know to modify state in some other process (especially one that hasn't started yet).

People that use doskey to setup their initial command shell environments typically use the /K option (often via a shortcut) to run a batch file which does all the common setup (like- set window's title, colors, etc).

cmd.exe /K env.cmd

env.cmd:

title "Foo Bar"
doskey np=notepad++.exe $*
...
Leigh
  • 28,765
  • 10
  • 55
  • 103
josh poley
  • 7,236
  • 1
  • 25
  • 25
  • 9
    This works for the command prompt in which I run this command. But if I close the window and open a new command prompt. It doesn't remember the np command. Is there any way I can make the command prompt remember so I don't have to run this each time I open a new command prompt? – Romonov Dec 13 '13 at 21:37
  • 6
    Same behavior without changing the PATH: `doskey npp="C:\Program Files (x86)\Notepad++\notepad++.exe" $*` – Matt Bierner Oct 09 '14 at 20:23
  • 6
    doskey.exe has nothing to do with cmd.exe. It sets an alias for the current or a specified executable in the console window, which is hosted by an instance of conhost.exe. Console aliases are matched and substituted at the beginning of a line of input before the client application (e.g. cmd.exe or powershell.exe) reads the line. They can't be used generically as commands, e.g. not in batch files or piped into. – Eryk Sun Aug 02 '15 at 09:31
  • Hi, I have used this with cmder to open phpstorm...it opens phpstorm but it keeps opening my last opened project and not the project directory I am currently in...How do I get this to open whichever DIR I am in? – CodeConnoisseur Dec 17 '19 at 00:11
  • @PA-GW: Did you use "phpstorm $*" in the doskey command? Did you try `phpstorm .` (note the dot as a shortcut for "current dir"). – user unknown Jan 14 '21 at 17:58
  • This method works very well with Windows Terminal since you can give `/K env.cmd` in the `Command line` attribute – Warpstar22 Aug 12 '22 at 14:56
212

If you're just going for some simple commands, you could follow these steps:

  1. Create a folder called C:\Aliases
  2. Add C:\Aliases to your path (so any files in it will be found every time)
  3. Create a .bat file in C:\Aliases for each of the aliases you want

Maybe overkill, but unlike the (otherwise excellent) answer from @Argyll, this solves the problem of this loading every time.

For instance, I have a file called dig2.bat with the following in it:

@echo off
echo.
dig +noall +answer %1

Your np file would just have the following:

@echo off
echo.
notepad++.exe %1

Then just add the C:\Aliases folder to your PATH environment variable. If you have CMD or PowerShell already opened you will need to restart it.

FWIW, I have about 20 aliases (separate .bat files) in my C:\Aliases directory - I just create new ones as necessary. Maybe not the neatest, but it works fine.

UPDATE: Per an excellent suggestion from user @Mav, it's even better to use %* rather than %1, so you can pass multiple files to the command, e.g.:

@echo off
echo.
notepad++.exe %*

That way, you could do this:

np c:\temp\abc.txt c:\temp\def.txt c:\temp\ghi.txt

and it will open all 3 files.

Alvaro Flaño Larrondo
  • 5,516
  • 2
  • 27
  • 46
roryhewitt
  • 4,097
  • 3
  • 27
  • 33
  • If you don't want your commandline to wait on closing notepad++, then you can use `@echo off START notepad++.exe %*` – Sornakumar Jan 27 '18 at 21:11
  • 8
    I personally do use this method for a long time. This is one such very easy to do method if someone does not want to go on the way of `doskey`. – bantya Mar 06 '18 at 16:52
  • 7
    One advantage of this method (cmd files as aliases) is that if you use WSL (Linux subsystem for Windows) these cmds are available in bash as well. Though often (depending what you are aliasing) you need to do some path manipulation using wslpath.sh or similar before you call the cmd file – Alex Perry Apr 14 '18 at 19:05
  • This solution won't work for things like `DOSKEY ls=ls --color=auto &*`. – Qwerty Sep 11 '18 at 17:30
  • 1
    @Qwerty, in a comment on another answer above, I pointed out that I *never* create aliases with the same name as the underlying command, so I guess it never occurred to me! Actually, couldn't you fully qualify the `ls` command within your `.bat` file? – roryhewitt Sep 11 '18 at 23:35
  • 1
    @roryhewitt Oh yes, specifying the full path to the `ls.exe` should definitely work. Good point. I have used the doskey alternative though. – Qwerty Sep 12 '18 at 18:36
  • wow! though it is a lengthy solution but amazing simple and easy to implement – Anmol Saraf Sep 18 '18 at 02:29
  • 11
    Might want to add %* instead of %1 to pass in all the arguments as opposed to just the first. – Mav Oct 04 '18 at 03:07
  • @Mav - good point. In these examples, there's only a single argument anyway, but your point is well taken. – roryhewitt Oct 04 '18 at 16:15
  • Just allowed myself to apply a little improvement which I think was intended. %1 just forwards the first parameter, $* all of them. See https://ss64.com/nt/doskey.html for reference. – Cadoiz Mar 25 '19 at 19:42
  • 1
    Great! Now I can have PHP without need to install it, just using devilbox for docker and adding `docker exec --user devilbox dvlbx_php_1 php %*` – Alvaro Flaño Larrondo Dec 01 '19 at 01:11
  • 1
    What's the `echo.` for? – Cees Timmerman Jun 23 '20 at 23:05
  • 1
    @CeesTimmerman it just adds a blank line in the terminal output. Not really necessary in this case (where I'm opening an application), but in some cases that blank line makes it easier to see things – roryhewitt Jun 25 '20 at 02:23
44

Alternatively you can use cmder which lets you add aliases just like linux:

alias subl="C:\Program Files\Sublime Text 3\subl.exe" $*
  • 16
    Although this doesn't answer the question. It is important for people from a Linux background to understand that there is an alternative to Windows CMDs that can suit their immediate needs. – Joseph Casey Mar 31 '17 at 23:12
  • 2
    There are quite a few alternatives. Git for Windows comes with one, "git-bash". – cowlinator Dec 21 '18 at 23:54
  • To add alias in Cmder, see an example [here](https://stackoverflow.com/a/54478765/6064933). – jdhao Feb 01 '19 at 11:49
  • Hi, I have used this with cmder to open phpstorm...it opens phpstorm but it keeps opening my last opened project and not the project directory I am currently in...How do I get this to open whichever DIR I am in? – CodeConnoisseur Dec 17 '19 at 00:10
  • @PA-GW You might want to add `.` as argument to phpstorm to tell it to open the current directory. See [this](https://www.jetbrains.com/help/phpstorm/opening-files-from-command-line.html#) help entry from Jetbrains for more info and [this](https://www.jetbrains.com/help/phpstorm/working-with-the-ide-features-from-command-line.html#) for other command line options for phpstorm. – geisterfurz007 Jun 17 '20 at 06:51
  • Agree that whilst this doesn't answer the question, it answers the need better for many who will search for this question. – jabberwocky Feb 09 '21 at 12:54
35

Given that you added notepad++.exe to your PATH variable, it's extra simple. Create a file in your System32 folder called np.bat with the following code:

@echo off
call notepad++.exe %*

The %* passes along all arguments you give the np command to the notepad++.exe command.

EDIT: You will need admin access to save files to the System32 folder, which was a bit wonky for me. I just created the file somewhere else and moved it to System32 manually.

Velixo
  • 694
  • 6
  • 11
  • I already have a folder of little .bat utility files so I like this better than messing with the registry or a .cmd file – Rich Apr 21 '16 at 14:04
  • 1
    I just tried that and it doesn't work identically to calling Notepad++ directly. If you use wildcards in the filename you're opening, and call NPP directly, it works, e.g. you can do `"notepad++.exe *somefiles*"` and matching files will open. When I tried that with your suggested batch file, i.e. `"npp *somefiles*"`, it did open an NPP instance but did not open the files I passed. Any thoughts? – SSilk Aug 31 '16 at 13:58
  • worked like a charm, as for my case I wanted to run multiple PHP versions with different aliases like php7, phpx etc. and this one worked for me – Abdulbasit Mar 10 '22 at 07:36
19

Also, you can create an alias.cmd in your path (for example C:\Windows) with the command

@echo %2 %3 %4 %5 %6 > %windir%\%1.cmd

Once you do that, you can do something like this:

alias nameOfYourAlias commands to run 

And after that you can type in comman line

nameOfYourAlias 

this will execute

commands to run 

BUT the best way for me is just adding the path of a programm.

setx PATH "%PATH%;%ProgramFiles%\Sublime Text 3" /M 

And now I run sublime as

subl index.html
14

Console Aliases in Windows 10

To define a console alias, use Doskey.exe to create a macro, or use the AddConsoleAlias function.

doskey

doskey test=cd \a_very_long_path\test

To also pass parameters add $* at the end: doskey short=longname $*

AddConsoleAlias

AddConsoleAlias( TEXT("test"), 
                 TEXT("cd \\<a_very_long_path>\\test"), 
                 TEXT("cmd.exe"));

More information here Console Aliases, Doskey, Parameters

Qwerty
  • 29,062
  • 22
  • 108
  • 136
  • BTW, I made a new, much better answer below that allows you to register aliases for each cmd https://stackoverflow.com/questions/20530996/aliases-in-windows-command-prompt/59978163#59978163 – Qwerty Apr 22 '22 at 10:05
11

You want to create an alias by simply typing:

c:\>alias kgs kubectl get svc

Created alias for kgs=kubectl get svc

And use the alias as follows:

c:\>kgs alfresco-svc

NAME           TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
alfresco-svc   ClusterIP   10.7.249.219   <none>        80/TCP    8d

Just add the following alias.bat file to you path. It simply creates additional batch files in the same directory as itself.

  @echo off
  echo.
  for /f "tokens=1,* delims= " %%a in ("%*") do set ALL_BUT_FIRST=%%b
  echo @echo off > C:\Development\alias-script\%1.bat
  echo echo. >> C:\Development\alias-script\%1.bat
  echo %ALL_BUT_FIRST% %%* >> C:\Development\alias-script\%1.bat
  echo Created alias for %1=%ALL_BUT_FIRST%

An example of the batch file this created called kgs.bat is:

@echo off 
echo. 
kubectl get svc %* 
Steaton
  • 119
  • 1
  • 6
11

Naturally, I would not rest until I have the most convenient solution of all. Combining the very many answers and topics on the vast internet, here is what you can have.

  • Loads automatically with every instance of cmd
  • Doesn't require keyword DOSKEY for aliases
    example: ls=ls --color=auto $*

Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.

cmd greetings & aliases

How to make it work?

  1. Create a mac macro file with the aliases
    you can even use a bat/cmd file to also run other stuff (similar to .bashrc in linux)
  2. Register it in Registry to run on each instance of cmd
      or run it via shortcut only if you want

Example steps:

%userprofile%/cmd/aliases.mac

;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;================================ general info ================================
;= https://stackoverflow.com/a/59978163/985454  -  how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8  -  example doskey macrofile
;========================= loading with cmd shortcut ==========================
;= create a shortcut with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

alias=echo Opening aliases in Sublime... && subl %USERPROFILE%\cmd\aliases.mac
ga=grep --color "$1" %USERPROFILE%\cmd\aliases.mac

hosts=runas /noprofile /savecred /user:QWERTY-XPS9370\administrator "subl C:\Windows\System32\drivers\etc\hosts" > NUL

p=@echo "~~ powercfg -devicequery wake_armed ~~" && powercfg -devicequery wake_armed && @echo "~~ powercfg -requests ~~ " && powercfg -requests && @echo "~~ powercfg -waketimers ~~"p && powercfg -waketimers

ls=ls --color=auto $*
ll=ls -l --color=auto $*
la=ls -la --color=auto $*
grep=grep --color $*

~=cd %USERPROFILE%
cdr=cd C:\repos
cde=cd C:\repos\esquire
cdd=cd C:\repos\dixons
cds=cd C:\repos\stekkie
cdu=cd C:\repos\uplus
cduo=cd C:\repos\uplus\oxbridge-fe
cdus=cd C:\repos\uplus\stratus

npx=npx --no-install $*
npxi=npx $*
npr=npm run $*

now=vercel $*


;=only in bash
;=alias whereget='_whereget() { A=$1; B=$2; shift 2; eval \"$(where $B | head -$A | tail -1)\" $@; }; _whereget'

history=doskey /history
h=IF ".$*." == ".." (echo "usage: h [ SAVE | TAIL [-|+<n>] | OPEN ]" && echo. && doskey/history) ELSE (IF /I "$1" == "OPEN" (%USERPROFILE%\cmd\history.log) ELSE (IF /I "$1" == "SAVE" (echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history >> %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TAIL" (tail $2 %USERPROFILE%\cmd\history.log) ELSE (doskey/history))))

;=exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history >> %USERPROFILE%\cmd\history.log & ECHO Command history saved, exiting & timeout 1 & exit $*
exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history >> %USERPROFILE%\cmd\history.log & exit $*

;============================= :end ============================
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line.  It clears out the ';'
;= rem * macro. We're using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=

Now you have three options:

  • a) load manually with shortcut

    create a shortcut to cmd.exe with the following target :
    %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

  • b) register just the aliases.mac macrofile

  • c) register a regular cmd/bat file to also run arbitrary commands (similar to linux's .bashrc)
    see example cmdrc.cmd file at the bottom

note: Below, Autorun_ is just a placeholder key which will not do anything. Pick one and rename the other.

Manually edit registry at this path:

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]

  Autorun    REG_SZ    doskey /macrofile=%userprofile%\cmd\aliases.mac
  Autorun_    REG_SZ    %USERPROFILE%\cmd\cmdrc.cmd

Or import reg file:

%userprofile%/cmd/cmd-aliases.reg

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
"Autorun_"="%USERPROFILE%\\cmd\\cmdrc.cmd"

%userprofile%/cmd/cmdrc.cmd you don't need this file if you decided for b) above

:: This file is registered via registry to auto load with each instance of cmd.
:: https://stackoverflow.com/a/59978163/985454

@echo off
doskey /macrofile=%userprofile%\cmd\aliases.mac

:: put other commands here

cls
echo Hi Qwerty, how are you today?

cmd greetings & aliases

Qwerty
  • 29,062
  • 22
  • 108
  • 136
  • Do we need the "/macrofile" - I can't find info on that.. I get "'/macrofile' is not recognized as an internal or external command".. – Galivan Apr 19 '22 at 17:31
  • @Galivan It's `doskey /macrofile` – Qwerty Apr 22 '22 at 09:12
  • This is great, thanks Is there a way to use with PowerShell as well? – Utsav Barnwal Nov 25 '22 at 05:06
  • @UtsavBarnwal It seems that adding `/exename=powershell.exe` could make this work, like `doskey /exename=powershell.exe /macrofile=%userprofile%\cmd\aliases.mac`. But I did not test it. Then you could use this with a desktop shortcut. I bet there is a way to add it to registers too if we find the proper reg key. https://devblogs.microsoft.com/premier-developer/getting-doskey-macros-to-work-in-powershell/ – Qwerty Nov 25 '22 at 18:31
6

Actually, I'll go you one better and let you in on a little technique that I've used since I used to program on an Amiga. On any new system you use, be it personal or professional, step one is to create two folders: C:\BIN and C:\BATCH. Then modify your path statement to put both at the start in the order C:\BATCH;C:\BIN;[rest of path].

Having done that, if you have little out-of-the-way utilities that you need access to simply copy them to the C:\BIN folder and they're in your path. To temporarily override these assignments, you can add a batch file with the same name as the executable to the C:\BATCH folder and the path will find it before the file in C:\BIN. It should cover anything you might ever need to do.

Of course, these days the canonical correct way to do this would be to create a symbolic junction to the file, but the same principle applies. There is a little extra added bonus as well. If you want to put something in the system that conflicts with something already in the path, putting it in the C:\BIN or C:\Batch folder will simply pre-empt the original - allowing you to override stuff either temporarily or permanently, or rename things to names you're more comfortable with - without actually altering the original.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
David
  • 71
  • 2
  • 1
  • 1
    This is the same answer as roryhewitt. – Jean-François Fabre Nov 08 '16 at 19:23
  • 2
    Actually, no it's not. I said 'one better'. The built-in option to override or underride an override that's already in place. The simple segregation of executables from batch files. And rory's solution does not specify *where* in the path the folder should go. Most will therefore put it at the end of the path. Being at the end instead of the beginning, his solution will not allow overrides in the first place. Rory's solution is approximately the same as the solution I myself originally arrived at - 25 years ago. I've refined the model somewhat since then. – David Nov 22 '16 at 15:54
  • 3
    Whatever. People using an Amiga cannot be all bad. – Jean-François Fabre Nov 23 '16 at 20:50
  • Fair enough :) In my case, the Aliases folder IS at the beginning of the path, but in any case, I personally don't want to override the default - my aliases always have different names. So I use 'dig2' and 'digx' as aliases to 'dig', but still have 'dig' available (without needing to specify its folder). Also +1 for Amiga :) – roryhewitt Jan 12 '17 at 18:52
  • Nice memories , I've also renamed bat file to startup-sequence :) – Erdinç Çorbacı Nov 07 '19 at 20:50
5

Expanding on roryhewitt answer.

An advantage to using .cmd files over DOSKEY is that these "aliases" are then available in other shells such as PowerShell or WSL (Windows subsystem for Linux).

The only gotcha with using these commands in bash is that it may take a bit more setup since you might need to do some path manipulation before calling your "alias".

eg I have vs.cmd which is my "alias" for editing a file in Visual Studio

@echo off
if [%1]==[] goto nofiles
start "" "c:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" /edit %1
goto end
:nofiles
start "" "C:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" "[PATH TO MY NORMAL SLN]"
:end

Which fires up VS (in this case VS2012 - but adjust to taste) using my "normal" project with no file given but when given a file will attempt to attach to a running VS opening that file "within that project" rather than starting a new instance of VS.

For using this from bash I then add an extra level of indirection since "vs Myfile" wouldn't always work

alias vs='/usr/bin/run_visual_studio.sh'

Which adjusts the paths before calling the vs.cmd

#!/bin/bash
cmd.exe /C 'c:\Windows\System32\vs.cmd' "`wslpath.sh -w -r $1`"

So this way I can just do

vs SomeFile.txt

In either a command prompt, Power Shell or bash and it opens in my running Visual Studio for editing (which just saves my poor brain from having to deal with VI commands or some such when I've just been editing in VS for hours).

Alex Perry
  • 335
  • 3
  • 9
3

Make a new folder anywhere on your system dedicated for aliases. Make a new file called whatever you want to name the alias with the .cmd extension. Write all commands in the file, such as

cd /D D:\Folder
g++ -o run something.cpp

Copy the folder's path.

Go to Settings > System > About > Advanced system settings > Environment Variables...

Now find the Path variable under the System variables section. Click on it once and click Edit. Now click New and paste the copied text.

Click OK, OK and OK. Restart your Powershell/cmd prompt and voila, you got your persistent alias! You can use the same folder to make other aliases too without needing to change Path variable again!

Anm
  • 447
  • 4
  • 15
2

This solution is not an apt one, but serves purpose in some occasions.

First create a folder and add it to your system path. Go to the executable of whatever program you want to create alias for. Right click and send to Desktop( Create Shortcut). Rename the shortcut to whatever alias name is comfortable. Now, take the shortcut and place in your folder.

From run prompt you can type the shortcut name directly and you can have the program opened for you. But from command prompt, you need to append .lnk and hit enter, the program will be opened.

BarathVutukuri
  • 1,265
  • 11
  • 23
1

Since you already have notepad++.exe in your path. Create a shortcut in that folder named np and point it to notepad++.exe.

Shravan
  • 141
  • 7
1

My quick and dirty solution is to add a BAT file in any directory which is already in the PATH.

Example:

@ECHO OFF
doskey dl=aria2c --file-allocation=none $*
aria2c --file-allocation=none %**

So, the first time you run "dl" it will execute the bat file, but from the second time onwards it will use the alias.

Zibri
  • 9,096
  • 3
  • 52
  • 44
0

First, you could create a file named np.cmd and put it in the folder which in PATH search list. Then, edit the np.cmd file as below:

@echo off
notepad++.exe
0

If you'd like to enable aliases on per-directory/per-project basis, try the following:

  1. First, create a batch file that will look for a file named aliases in the current directory and initialize aliases from it, let’s call it make-aliases.cmd

    @echo off
    if not exist aliases goto:eof
    echo [Loading aliases...]
    for /f "tokens=1* delims=^=" %%i in (aliases) do (
       echo   %%i ^<^=^> %%j
       doskey %%i=%%j
    )
    doskey aliases=doskey /macros
    echo   --------------------
    echo   aliases ^=^> list  all
    echo   alt+F10 ^=^> clear all
    echo [Done]
    
  2. Then, create aliases wherever you need them using the following format:

    alias1 = command1
    alias2 = command2
    ...
    

    for example:

    b = nmake
    c = nmake clean
    r = nmake rebuild
    
  3. Then, add the location of make-aliases.cmd to your %PATH% variable to make it system-wide or just keep it in a known place.

  4. Make it start automatically with cmd.

    • I would definitely advise against using HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun for this, because some development tools would trigger the autorun script multiple times per session.

    • If you use ConEmu you could go another way and start the script from the startup task (Settings > Startup > Tasks), for example, I created an entry called {MSVC}:

      cmd.exe /k "vcvars64 && make-aliases",

      and then registered it in Explorer context menu via Settings > Integration> with Command: {MSVC} -cur_console:n, so that now I can right-click a folder and launch a VS developer prompt inside it with my aliases loaded automatically, if they happen to be in that folder.

      Without ConEmu, you may just want to create a shortcut to cmd.exe with the corresponding command or simply run make-aliases manually every time.

Should you happen to forget your aliases, use the aliases macro, and if anything goes wrong, just reset the current session by pressing Alt+F10, which is a built-in command in cmd.

Michael
  • 8,362
  • 6
  • 61
  • 88
sunny moon
  • 1,313
  • 3
  • 16
  • 30
0

As doskey does not work for PowerShell or Windows 10 terminal apps, I am sharing this solution.

Demo to create an alias in Windows 10. Alias to be expected with input parameters:

com=D:\website_development\laragon\bin\php\php-8.1.2-Win32-vs16-x64/php8 D:\website_development\laragon\bin\composer/composer.phar

Procedure:

  1. Create a folder named "scripts" in the C: drive.

  2. Inside the scripts folder, create com.bat

  3. Open com.bat

  4. Example for running composer command with specific PHP version:

    @echo off 
    set path=D:\website_development\laragon\bin\php\php-8.1.2-Win32-vs16-x64/php8 D:\website_development\laragon\bin\composer/composer.phar
    set args=%*
    set command=%path% %args%
    %command%
    
  5. Save it

  6. Click "Start"

  7. Search for "Edit Environment Variables"

  8. Click "Advanced"

  9. Add your "scripts" directory to PATH.

Now you can run the command as its alias.

Note: If you want to add a new alias, just create a new bat file.

Michael
  • 8,362
  • 6
  • 61
  • 88
Nayeem
  • 81
  • 5
0

I use Scoop. It, in turn, uses Shim utility to forward commands to the corresponding executables.

So it's similar to the .cmd file solution but with the Shim's .exe file.

My goal was to run podman.exe by docker command.

So I created a copy of shim .exe file (they all are in the %USERPROFILE%\scoop\shims which is in the PATH) with the appropriate name (docker.exe in my case). Plus created a configuration file for it (docker.shim) with the following content:

path = "<USERPROFILE>\scoop\apps\podman\current\podman.exe"

where <USERPROFILE> should be replaced by the content of the %USERPROFILE% variable.

If you need additional parameters for the executable, it might be provided to the Shim with the args = option.

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
-4

Using doskey is the right way to do this, but it resets when the Command Prompt window is closed. You need to add that line to something like .bashrc equivalent. So I did the following:

  1. Add "C:\Program Files (x86)\Notepad++" to system path variable
  2. Make a copy of notepad++.exe (in the same folder, of course) and rename it to np.exe

Works just fine!

balajimc55
  • 2,192
  • 2
  • 13
  • 15