55

Back in school, I used to have a .login file along the lines of

alias ll = ls -l  
alias dir = ls -Fhl  
alias web = cd ~/public/public_www/development  

I'd like to do that sort of thing with my XP box here at work, but most of the resources I've found online seem fairly complicated and heavy-duty. Is there a way to do this that doesn't involve mucking about in the registry or running a large batch file?

My original reason for asking this was that I only need the command line for one command in one specific folder, and I wanted to be able to get to that folder quickly when I launched the command line. But the accepted answer for this question is so good that I decided to ask about my original issue as a separate question: Change to default start folder for Windows command prompt.

1
  • A quick&dirty option is to just add the folder to the PATH variable. Right-click My Computer, choose Properties, go to Advanced, then Environment Variables. More info: stackoverflow.com/a/20773224/722036 Sep 10, 2016 at 9:56

7 Answers 7

85

Not many people seem to know about it, but you can use the doskey built-in macro tool, the only issue is that it doesn't save. There are many ways to work around this though.

usage:

doskey ls=dir

ls will now do a directory listing just like dir would.

If you want to use arguments with the commands, use this syntax:

doskey d=dir $*

As for the workaround to make them save:

  • save all aliases to a file in this format:
doskey ls=dir
doskey ..=cd ..

and place it in one of the directories in your path. Name it something short like a.cmd, so when you open cmd you can type a to load your aliases.

If typing an a and pressing Enter seems too much work, throw this into your AutoHotkey script:

WinWaitActive, C:\WINDOWS\system32\cmd.exe
Send {a}{Enter}

Loading aliases automatically:

You can change all shortcuts to cmd to point to %SystemRoot%\system32\cmd.exe /K C:\path\to\aliases.cmd, replacing C:\path\to\aliases.cmd with the location of your aliases file. If you typically run it from the run box, you can:

  • Rename the cmd executable to cmd2.exe for example, and replace it with a script or another executable which launches the above command (I wouldn't really recommend this method as a lot of apps depend on cmd)
  • Make a batch script and call it cmda (cmd with aliases) for example. Have it launch the above command and put this batch script somewhere in your path.
4
  • 1
    +1 NICE!!! Haven't seen (or remembered) Doskey for years!... (Playing the memories song in my head!) Oct 1, 2009 at 0:19
  • 19
    No need for an AutoHotkey script here. Windows provides a way to AutoRun a batch file whenever you launch cmd.exe: technet.microsoft.com/en-us/library/cc779439(WS.10).aspx I configure it to point to c:\dev\autorun.bat which loads doskey macros and runs other convenient utilities. Aug 16, 2010 at 22:15
  • I'm really surprised no one has suggested PowerShell it's pretty damned good. Dec 6, 2012 at 18:51
  • Does the defined macros work from the Win+R (Run) box ???
    – ZEE
    Jan 5, 2017 at 21:28
42

It's a simple as:

  1. Create a file with aliases, e.g. c:\bin\aliases:

    ls=dir /ONE $*
    cd=cd /d $*
    python=python -ic "" 
    ps=tasklist $*
    kill=taskkill /IM $*
    
  2. Create a file with all the stuff you want to run when cmd.exe is started, including loading the aliases with doskey e.g. c:\bin\cmd_autoruns.cmd:

    @echo off
    cls
    color 0A
    doskey /macrofile=c:\bin\aliases
    
  3. Create and run once a batch file (e.g. set_cmd_autorun.cmd) which will set the Command Processor Autorun key to our cmd_autoruns.cmd:

    reg add "hkcu\software\microsoft\command processor" /v Autorun /t reg_sz /d c:\bin\cmd_autoruns.cmd
    

As an alternative to set_cmd_autorun.cmd it is also possible to instead create a .reg file like the one below and then merge it with a double click:

REGEDIT4

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009
"DefaultColor"=dword:00000000
"EnableExtensions"=dword:00000001
"PathCompletionChar"=dword:00000009
"Autorun"="c:\\bin\\cmd_autoruns.cmd"
3
  • 'color OA' should probably be 'color 0A'.
    – cseaton
    Jun 2, 2011 at 23:29
  • 1
    You only need the "Autorun"="..." line under the [HKEY_...] line, unless you want to explicitly set the other keys too.
    – c24w
    Feb 26, 2013 at 11:38
  • My path had spaces and having trouble in adding to the registry. I used following: Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor] "Autorun"="\"C:\\Path has spaces\\foldername\\cmd_autoruns.cmd\"" Jan 1, 2020 at 6:48
5

My answer is similar to vriolk's

I created a .bat file that contained my macros (e.g. c:\winscripts\autoexec.bat):

@doskey whereis=c:\winscripts\whereis.cmd $*
@doskey ls=dir /b $*
@doskey l=dir /od/p/q/tw $*

and then from a cmd prompt ran "cmd /?" to find the registry key to edit for the cmd autorun:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
  and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun

using regedit, add the path for your macro batch file to the AutoRun value (add the AutoRun key if it's not there):

c:\winscripts\autoexec.bat

now whenever you run "cmd" from the Start->Run prompt, this autoexec.bat will also run and create the doskey macros for you.

By the way, whereis.cmd contains this:

@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i

which searches your PATH variable for the term you provide:

c:>whereis javaw
c:\jdk\bin\javaw.exe
1
  • BTW instead of whereis hack you can use where which is a builtin command Nov 19, 2014 at 12:37
2

a very quick and dirty way to have a ready shortcut, that doesn't require a lot of fuss - is to create a batch file named after the alias, in one of the directories that are a part of the PATH environment variable. For example, i wanted to invoke Notepad++ through an alias, so i created npp.bat in C:\WINDOWS that contained the following:

"c:\Program Files\Notepad++\notepad++.exe" %1 %2 %3 %4 %5

now npp command can be used from any cmd shell, without autorun files and/or excursions to the registry

1

You can create .cmd files and place them someplace in your %PATH% (such as C:\Windows). To use your web alias as an example:

@C:
@cd \inetpub\wwwroot

Would do something like:

M:\> web
C:\inetpub\wwwroot>

I'm not aware of any way to make a flat .aliases style file.

0

The way I did it was with a quick python script:

import sys
import string
import os
import glob

def listAll():
        for infile in glob.glob("c:\\aliases\\*.bat"):
            fileName = infile
            fileName = fileName[len("c:\\aliases\\"):len(fileName)-4]
            fileContents = open("c:\\aliases\\" + fileName + ".bat", "r")
            fileContents.readline()
            fileContentString=fileContents.readline()
            fileName += " is aliased to "
            fileName += fileContentString[0:len(fileContentString)-3]
            print fileName

def listSome(which):
        for infile in glob.glob("c:\\aliases\\*.bat"):
            fileName = infile
            fileName = fileName[len("c:\\aliases\\"):len(fileName)-4]
            fileContents = open("c:\\aliases\\" + fileName + ".bat", "r")
            fileContents.readline()
            fileContentString=fileContents.readline()
            if fileName.find(which)==0:
                fileName += " is aliased to "
                fileName += fileContentString[0:len(fileContentString)-3]
                print fileName

if len(sys.argv)>1:
    if sys.argv[1]!="-p":
        file = open("c:\\aliases\\"+sys.argv[1]+".bat", "w")
        file.write("@ECHO OFF\n")
        counter=0
        totalInput=""
        counter=0
        for arg in sys.argv:
            if counter > 1:
                totalInput+= arg + " "
            counter+=1

        if totalInput.find(".exe")!=-1:
            file.write("\"")

        counter=0

        for arg in sys.argv:
            if counter > 1:
                file.write(arg)
                if sys.argv[1]==sys.argv[2]:
                    if counter==2:
                        file.write(".exe")
                temparg=str(arg)
                if temparg.find(".exe")!=-1:
                    file.write("\"")
                file.write(" ")
            counter+=1
        file.write("%*")

        print "Aliased " + sys.argv[1] + " to " + totalInput
    else:
        if len(sys.argv)>2:
            listSome(sys.argv[2])
        else:
            listAll()
else:
    listAll()

Apologies for the poor scripting, but the usage is quite nice, imo. Place it somewhere in your path, add .py to your PATHEXT, and add c:\aliases to your PATH too (or change it, whatever suits), then use:

alias <command> <action>

to alias (Yep, no =, though it wouldn't be hard to add a .split in there), and:

alias -p <command or part of>

To display what something is.

Hackish, but stupidly useful. There's an equivalent unalias script, but I'm sure you can work that one out.

edit: This obviously requires python, written on v26 but will probably work in anything recent. As before, sorry for the quality :)

edit2: Actually, something like this but to add to the doskey stuff would be better. You can add startup commands to cmd with the autorun registry key, too, so that could be much cleaner.

2
  • 1
    Nice solution, though a bit overkill for my needs.
    – Pops
    Oct 1, 2009 at 14:02
  • Indeed it is. I just like having control over how my stuff works, is all :P
    – Phoshi
    Oct 1, 2009 at 15:50
0

Batch files support a macro creation syntax. You can just declare macros as variables, and pass them arguments like functions.

Macros is a little bit hard to write, but they can be more powerful, faster, efficient than DOSKEY based macros.

Your three examples can be done with macros, but the syntax will be different in windows.

For persistent macros, you can create a MACROS.cmd file with macros, and call it in your script or add to AutoRun registry key (As @user29888 said).

How-to: Create Batch file macros

A macro allows you to embed blocks of code in a variable. Like calling a subroutine or function this allows reusing the same block of code multiple times, the difference is that by placing the code in a variable the performance will be much faster.

This is an advanced technique but can be very useful in scripts that include large blocks of code or looping commands where the performance of other methods is too slow.

A macro which runs exit /b

set _ex=exit /b

You can then exit a subroutine with:

%_ex%

A macro which lists all the .XLS files in a folder:

Set _macro=Dir c:\demo\*.xls We can now run the Macro like this: %_macro% A macro to allow comments within bracketed code blocks [source]:

Set "[=rem/||(" & set "]=)"

For %%G in (first second) do (
   Echo first not commented line of the %%G execution
   %[%
       this is a multi line
       comment
   %]%
   Echo second not commented line of the %%G execution
)

So far so like the DOSKEY command, but to make this more powerful you will want to pass arguments to the macro, in the example above you might want to pass the name of the folder to be listed.

Passing arguments to a macro is not particularly easy, the best method (discovered by Jeb) is to place a For /L command within the macro, set to run 2 steps each time the macro is run:

In the first step the arguments are stored in a variable (argv)

In the second step the main body of the macro runs and can (optionally) read the variable

The basic structure of the macro definition:

Set _macro=For /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.) else setlocal enableDelayedExpansion ^& Set argv=, 

%_macro% arg1 arg2

:: The macro will expand to:
:: for /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.) else setlocal enableDelayedExpansion & Set argv=, arg1 arg2

:: which is equivalent to:
::    setlocal enableDelayedExpansion
::    Set argv= arg1 arg2
::    Echo Main MACRO goes here.

Examples:

@echo off
cls
setlocal DisableDelayedExpansion
set LF=^


::Above 2 blank lines are required - do not remove
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

set _macrodemo=for /L %%n in (1 1 2) do if %%n==2 (%\n%
     for /F "tokens=1 delims=, " %%G in ("!argv!") do (%\n%
        echo _argument1=%%G %\n%
        set "_argument1=!%%~G!"%\n%
        dir !_argument1!\*.xls%\n%
     ) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,

set "_testfolder=c:\demo"
%_macrodemo% _testfolder

In a macro where more than one argument need to be passed, these will become tokens 2,3,4... in the FOR / F command.

A library of macros can be defined by running a single MACROS.CMD batch file, allowing the library macros to be used in multiple batch files.

Source: https://ss64.com/nt/syntax-macros.html

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .