When Read-Host doesn’t quite cut it

Ninety percent of the time when you are writing PowerShell code, you can use parameters in advanced functions to get the data you need to get from a user. However, there are times that you may want to have a bit more control over the user experience. Out of the box, PowerShell provides a cmdlet called Read-Host.

image

From here you can use the variable in your code

image

This is cool but what if you want to offer choices to the user, and what if you want to customize the caption in the window in addition to the actual message. It turns out PowerShell has some messaging capabilities built in that are not exposed as direct Cmdlets. If you have used –confirm and –whatif on some Cmdlets, you have probably seen this UI.

image

I thought it would be pretty cool to be able to use this functionality with my own custom choices, caption, and message. I wrote a function called New-Choice that is up on Poshcode

Here are some example of using the function.

In PowerShell.exe

image

In ISE

image

And even in PowerGUI

image

In summary, this function provides a great way to provide a rich user experience and maintain control of possible inputs the user could provide.

Comments are closed