Sunday, 19 March 2017

Adding a `.cmd` shell wrapper for an executable

On Windows, to make an `.exe` visible on the command line, the standard way is to append the `.exe`'s location to the `PATH` environment variable. An alternative method is to create a `.cmd` shell wrapper for the `.exe` in a folder that is in `PATH`. On my computer, I created a specific folder, `C:\ShellWrappers`, to store shell wrappers, and added its location to `PATH`.

An example shell wrapper, `git.cmd`, is shown below.

@echo off
"C:\Program Files\Git\bin\git.exe" %*

`@echo off` disables echoing, and `%*` passes along all incoming arguments to the `git` executable.

You can invoke `git.cmd` as simply `git`:

git status

The `PATHEXT` environment variable lists extensions of executable files that can be executed without their file extension:

.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW;.CPL

Network Limitation

`.cmd` shell wrappers fail to work if have `cd`-ed to a network location; it causes the `.cmd` to be run in the `C:\Windows` directory. This directory change invalidates relative paths passed as arguments. The article, Adding an `.rb` shell wrapper for an executable, shows a similar approach using Ruby that works in a network location.