Use alias to run a loop

430 Views Asked by At

I would like to be able to manually type an 'alias' keyword into the command console and have it execute the following command a specified number of times.

taskkill /PID "%PID%" /f >nul 2>&1

I found this command which will run a loop:

for /l %x in (1, 1, 5) do

It works fine for simple commands like echoing text, but when I run the following (without the >nul 2>&1 just for the purposes of this test)

for /l %x in (1, 1, 5) do taskkill /PID "%PID%" /f

it stops after one time (displaying a 'success' message) instead of repeating the same command a further 4 times.

How can I get the command to execute multiple times without it stopping after each instance?

And once that's been achieved, how can I run that command from an alias?

I understand that certain characters will need to be escaped when the command is put into a batch file

set "close=taskkill /PID "%PID%" /f >nul 2>&1"
doskey close=taskkill /PID "%PID%" /f ^>nul 2^>^&1

and that double percentage character will be needed for %x loop command, but I still don't know what syntax to use to run the looping command when a specified 'alias' keyword is typed.

1

There are 1 best solutions below

3
On

From a commandline:

Note: > is at start of line to represent the prompt.

>doskey close=for /l %x in (1, 1, 5) do taskkill /pid ^%pid^% /f
>set "pid=10"
>close

is to set a doskey macro to use %pid%. Set pid to a value i.e 10 and then execute the macro.

>doskey close=for /l %x in (1, 1, 5) do taskkill /pid $1 /f
>close 10

is to set a doskey macro to use 1st argument as pid. Execute the macro using argument i.e. 10.


From a batch file to set doskey:

doskey close=for /l %%x in (1, 1, 5) do taskkill /pid %%pid%% /f

or set as an argument to pass the pid.

doskey close=for /l %%x in (1, 1, 5) do taskkill /pid $1 /f

Execute the macroes like the 1st 2 commandline examples.


The command in the macro will run 5 times. Running the macro is shown in commandline examples.