patternMinor
DOS batch script to open file explorer
Viewed 0 times
scriptfileopenexplorerbatchdos
Problem
I wrote a script that you can use to open the file explorer from command line like
(I’m not very happy with the way I define the relationship mnemonic folder.)
Remarks, anyone?
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
...Solution
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
e.cmd
This uses a relatively obscure feature of the
Naturally, in the real version, you'd want to specify the full path to the
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
Now just modify the script so that we specify the delimiter. To do that change the part of the line that says
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\Bine.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 ScriptingNow 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.Code Snippets
db D:\Alex\Dropbox
bin D:\Alex\Scripts\Bin@echo off
FOR /F "tokens=1,2" %%i in (e.txt) do if "%~1" EQU "%%i" ( explorer "%%j" & EXIT /B )
ECHO Invalid target %target%.sp=D:\Alex\Scripts\Advanced ScriptingContext
StackExchange Code Review Q#128362, answer score: 3
Revisions (0)
No revisions yet.