Published in Articles on by Michiel van Oosterhout ~ 2 min read

Remember how we added a line to the AutoRun script in part 1 to call the Commando script, but we left the implementation for later? Now that we have designed our extension mechanism (see part 2 and part 3), we can finally implement the missing piece: initialization.

Commando: a Windows Command Line extension system

The initialization should do 3 things: ensure the functions exported by extensions become readily available, record macros on behalf of extensions that define them, and install each extension.

Initialization

The Windows PowerShell script below creates the Commando script, a script that initializes the extension system for Windows Command Processor:

# Declare the Commando script contents
$script = @"
@echo off
if defined CMD (goto :EOF) else (set CMD=%~dp0)

setlocal enabledelayedexpansion
for /d %%d in ("%~dp0*") do (
    if exist "%%d\macros.txt" doskey /macrofile="%%d\macros.txt"

    for %%f in ("%%d\*.cmd") do (
        for /f "tokens=1,* delims=." %%x in ("%%f") do (
            if not %%~nx==Extend doskey %%~nd::%%~nx="%%~f" $*
        )
    )
)
endlocal

for /d %%d in ("%~dp0*") do (
    if exist %%d\Extend.cmd (
        call "%%d\Extend.cmd"
    )
)
"@

# Ensure the directory exists
$path = "$Env:LOCALAPPDATA\Commando"
$_ = New-Item $path -Force -ItemType Directory

# Create the Commando script
$path = "$path\Commando.cmd"
Set-Content -Path $path -Value $script

The initialization runs only once per session by checking the CMD environment variable. For each extension, it passes the macros.txt file to doskey for recording, records a macro for each exported function, and runs the extension's installation script (Extend.cmd).

Summary

Commando, an extension system for Windows Command Processor is in place, and we can now start creating useful extensions. Extensions can export functions, define macros, and provide a one-time installation script.

(The follow-up article to this series, Intercepting commands in Windows Command Processor, adds a significant new capability to the extension system.)

Updates

  • Changed the initialization to call extensions' Extend.cmd in global scope.