Is it possible to implement the subcommand pattern in PowerShell? Something like:
command [subcommand] [options] [files]
Examples: Git, svn, Homebrew
What would be the general architecture? A single function that delegates the actual work to script blocks? Each subcommand isolated in its own PS1
file that is dot-sources by the primary script? Would PowerShell's various meta-data functions (e.g. Get-Command
) be able to 'inspect' the subcommands?
I thought of this pattern and found two ways of doing this. I did not find real applications in my practice, so the research is rather academic. But the scripts below work fine.
An existing tool which implements this pattern (in its own way) is scoop.
The pattern subcommand implements the classic command line interface
This pattern introduces a single script
app.ps1
which provides commands instead of providing multiple scripts or functions in a script library or module. Each command is a script in the special subdirectory, e.g. ./Command.Get available commands
Invoke a command
Get command help
The script app.ps1 may contain common functions used by commands.
splat.ps1 (as such app.ps1) - pattern with splatting
Pros:
-?
works for help as it is (short help).Cons:
dynamic.ps1 (as such app.ps1) - pattern with dynamic parameters
Pros:
Cons:
-help
.Scripts
splat.ps1
UPDATE: Used
$_Command
instead of$Command
to avoid conflicts with partial parameter names like-c
, see comments.dynamic.ps1
UPDATE: Added more known common parameters.