/* ]]> */
Sep 032011
 

If you have ever developed a user-interactive script then you are well aware of the need to provide user choices and validate input. It seems that I’ve done this hundreds of times, continuously re-inventing code that performs three simple functions:

  1. Present the user with choices
  2. Accept input from the user
  3. Validate the user’s choice

To that end, I developed the “SelectFromList” function. Note, to use this function, you must also include the “isNumeric” function.

Here are the steps needed to use this function:

  1. Create a string array containing the choices that you will present to the user
  2. Call the SelectFromList function, passing the string array created in step 1 and receive a response to a variable
    Example: $choice = SelectFromList $ArrayOfChoices
  3. Test for a non-null response in the value returned from the function call
  4. A non-null response will be the numeric index value of the users choice from the selection array
  5. A null response indicates that the user quit without making a choice

The user is not permitted to make an invalid choice. If an invalid choice is received, the user is re-prompted for a valid response.


Screenshot:

Powershell SelectFromList Screenshot

Powershell SelectFromList Screenshot

Code:

 Posted by at 9:49 am

  4 Responses to “HowTo Make Menus in PowerShell”

  1. so, what happens when the user selects the first option ….

  2. is re-using $sel a good idea – I’m running into all kinds of logic errors.

  3. if ($sel) {
    should be
    if ($sel -ne $null) {
    or else if you choose the first option, it will resolve to false (0) …

  4. Jordon – you are absolutely right! Not sure how that got past my QA process :)

    Your suggested correction has been made to the code sample.

    Thanks!

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Page optimized by WP Minify WordPress Plugin