Home > other >  Windows Batch Files: How can I append to a *.bat or *.cmd file from within itself?
Windows Batch Files: How can I append to a *.bat or *.cmd file from within itself?

Time:09-17

I'm trying to implement a slight modification to the code provided by @Argyll in this SO answer, specifically changing:

DOSKEY alias=notepad %USERPROFILE%\Dropbox\alias.cmd

to:

doskey alias=echo doskey $*>>%0

But the redirection fails when I use this new alias, and I simply get doskey <whatever I typed after alias> echo'ed to the console as per usual :-(

As you can probably tell, I'm a batch script noob, so what am I doing wrong here? MTIA :-)

CodePudding user response:

You need to escape the redirection, else the redirection is active in the moment where you call doskey alias=echo doskey $*>>%0, it appends the output of the doskey command (which is always empty in this case) to the current batch file.

But if you modify your line to

doskey alias=echo doskey $*^>^> "%~f0"

This creates a macro named alias like

alias=echo doskey $* >> C:\myfull\path\to\myBatch.bat

I use %~f0 for the full path, else the macro could be defined like

alias=echo doskey $* >> myBatch.bat

That will obviously fail, if you're not in the correct directory

  • Related