Introduction

The solution to saving the Windows Command Prompt history using the DOSKEY utility is already well known, but this post will show how it can be done automatically every time you exit cmd.exe. By consensus the best workaround is to use the tool called Clink or Cmder (which uses Clink), however this article is simply meant to focus on doing exactly what the title says: Save Windows Command Prompt History on Exit. One of the caveats of using this method is that it requires you to type exit to close every cmd.exe session in order to save the history.

The credit goes to the user pbarney on this serverfault thread.

Solution

You can get the zip file that contains the code mentioned below here. This solution expects to use the %USERPROFILE% directory as the location where autoexec.bat resides.

  • autoexec.bat
    This is the BAT script that will be run every time a command prompt session is loaded. The primary purpose of this is to create the exit macro that calls doskey to save the history to a file called commands.log.
@echo off
if "%AUTOEXEC%" EQU "1" goto :eof
SET AUTOEXEC=1
echo Loading macros.

rem  remap exit command to save a copy of the command line history to a log before exiting.
DOSKEY exit=(echo/ ^& echo **** %date% %time% ****) $g$g %USERPROFILE%\commands.log ^& doskey /history $g$g %USERPROFILE%\commands.log ^& ECHO Command history saved, exiting ^& exit $*

rem  review previous command line entries:
DOSKEY history=notepad %USERPROFILE%\commands.log

rem  copy the current directory to the clipboard
DOSKEY cc=cd^|clip ^& echo %%CD%% copied to clipboard
  • HKLM_CommandProcessor.reg
    This creates the autorun registry string which runs autoexec.bat every time a cmd.exe session is loaded.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"AutoRun"="IF EXIST \"%USERPROFILE%\\autoexec.bat\" (CALL \"%USERPROFILE%\\autoexec.bat\")"

Step-by-step

  1. The first step is to ensure that autoexec.bat is in your user profile directory.
  2. Run the HKLM_CommandProcessor.reg file to create the registry string that will run autoexec.bat every time a command prompt session is loaded. You may need to reboot after this step.
  3. Run a new command prompt session aka: Start Run cmd.exe.
  4. Type some commands to test.
  5. In order to save the history to the commands.log file in your user profile directory you need to close each cmd session by typing exit. Saving the history will not work if you skip this.

If you have any questions/comments regarding this article, click here or scroll down below (login isn't required to post comments and there's no waiting period).