5
\$\begingroup\$

I wrote a script that you can use to open the file explorer from command line like

e db --> opens my Dropbox folder (e.cmd is the name of the script)
e bin --> opens my script folder

(I’m not very happy with the way I define the relationship mnemonic <--> folder.)
Remarks, anyone?

@ECHO OFF

SET "target=%~1"

if "%target%" EQU "" (
    ECHO No target specified.
    EXIT /B
)

SET folder=""
CALL :set_folder_%target% 2> nul
if %folder% EQU "" (
    ECHO Invalid target %target%.
    EXIT /B
)

explorer %folder%
EXIT /B

:set_folder_db
SET folder="D:\Alex\Dropbox" & EXIT /B

:set_folder_bin
SET folder="D:\Alex\Scripts\Bin" & EXIT /B

...
\$\endgroup\$
  • 1
    \$\begingroup\$ Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. \$\endgroup\$ – Vogel612 May 15 '16 at 10:51
3
\$\begingroup\$

It's not terrible as it is, but you're right to wonder if there's a better way. As you noticed already, it would be nice to keep the associations between the abbreviation and the corresponding directory in one place.

Fortunately, there's a very slick way to to that. First, create a text file file that contains just the file associations:

e.txt

db      D:\Alex\Dropbox
bin     D:\Alex\Scripts\Bin

e.cmd

@echo off
FOR /F "tokens=1,2" %%i in (e.txt) do if "%~1" EQU "%%i" ( explorer "%%j" & EXIT /B )
ECHO Invalid target %target%.

This uses a relatively obscure feature of the FOR command that allows us to parse a file. You can read more about that by executing HELP FOR from the command line.

Naturally, in the real version, you'd want to specify the full path to the e.txt file.

Allowing spaces in directory names

If you might have spaces in the directory names, you can do so with little additional effort. For example, we can use = for the delimiter in the text file so that each line now looks like this:

sp=D:\Alex\Scripts\Advanced Scripting

Now just modify the script so that we specify the delimiter. To do that change the part of the line that says "tokens=1,2" to read "tokens=1,2 delims==" and that's it.

\$\endgroup\$
  • \$\begingroup\$ This is great, thanks. I can even make the script parse itself if I come up with something like REM [mnemonic] [folder] \$\endgroup\$ – Alex Janzik May 14 '16 at 20:13
  • \$\begingroup\$ If you choose to have it all in one file, you can use skip=4 to skip over the code lines. \$\endgroup\$ – Edward May 14 '16 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.