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

Recently we created several extensions for Windows Command Processor. The first extensions added support for using ~ to refer to the current user's home directory (e.g. cd ~\Desktop), the second set of extensions improved the experience of deleting and creating directories (rmdir . to remove the current directory and mkdir /g to create a directory and navigate to it). In this article we will create one more extension, because why not?

path entries on separate lines

The path built-in command, when executed without any parameters, prints PATH= followed by the value of the PATH environment variable. The value is a semicolon-separated list of directories. When the value is empty path prints PATH=(null).

The `path` command on Windows
The path command on Windows

The Windows PowerShell script below installs an extension named PathLines, which prints each directory on a separate line, and prints nothing if the value is empty.

# Declare the filter script contents
$script = @"
@echo off
setlocal enabledelayedexpansion

for /f "delims=; tokens=1,*" %%a in ("%~1") do (
    if "%%~b"=="" (set next=%%~a) else (set next=call %%~a "%%b")
)

set count=0
shift
:loop_params
set next=%next% %1 && shift && if not "%~1"=="" set /a count+=1 && goto loop_params

if not %count%==0 (
    %next%
) else (
    for /f "delims== tokens=1,*" %%o in ('%next%') do (
        set p=%%p
    )

    :loop_path
    for /f "delims=; tokens=1,*" %%p in ("!p!") do (
        if not "%%~p"=="" if not %%p==^(null^) (
            echo %%p
        )

        if not "%%~q"=="" (
            set p=%%q
            goto loop_path
        )
    )
)

endlocal
"@

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

# Create the filter scripts
Set-Content -Path "$path\path.filter.cmd" -Value $script

The filter starts with the standard for command and loop (here labeled loop_params) to set next, but also uses the loop labeled loop_params to count the number of parameters in count. If count is not 0 then the filter simply calls next, otherwise the filter splits the output on = and captures the part after the first = in the p variable. Then it uses the loop labeled loop_path to split p on ; and print each value %%p on a separate line (e.g. echo %%p), unless the value is (null).

The output of the `path` command on Windows rendered with newlines
The output of the path command on Windows rendered with newlines

Summary

As we can see from this extension and the previous extensions, it's suprisingly simple to write small extensions to improve life on the command line. Typically 30 lines of code can accomplish a meaningful improvement.