Show-Command is a really handy PowerShell cmdlet. Jeff Hicks gave a great presentation at the PowerShell Deep Dive about how to create simple GUIs without having to resort to WinForms or WPF. In his talk he showed off Show-Command and other cmdlets like Out-GridView. Recently, we have been providing some simple solutions to customers using Show-Command to provide a simple interfaces that even non-techies can use. One of the caveats with Show-Command against the stock cmdlets is that there are a large number of possible parameters that will be exposed in the UI. This can be just as intimidating and hard to use as the command line.
Instead of providing the user with a raw cmdlet, it’s possible to use Show-Command and a function. Additionally, we can use the ValidateSet attribute to dynamically provide a predefined list of possible selections that they can make for any of the parameters. Using Invoke-Expression to create a function from a here-string, we can generate a function on the fly.
We can also remove the common parameters with the NoCommonParameters parameter on Show-Command. Due to a caveat with Show-Command, we need to use the PassThru parameter and use Invoke-Expression to actually execute the command after the user selects the input. My theory, is that since Show-Command has to have to a separate UI thread, executing a script containing Show-Command will cause strange results. This particular format causes Show-Command to return to the current thread and then process the command. Without the PassThru and Invoke-Expression, it seems to work in the ISE but not in a script!
The final result is a very simple UI.
It’s a simple little trick but it can be useful to easily wrap complex scripts for anyone to use.