Dynamic Pick Lists in Powershell

No one likes hard coded lists in script, especially long scripts that might be under change control. Add a new Internet Domain, Server, Mail Database, User Location and you have to go through the whole release test cycle..

However if you just have a Comma Separated Value (CSV) string you would like to present as an menu, perhaps loaded from an external text or XML file, this single function does just that. It takes a CSV string and presents the user with a list of choices and returns their selection for later use.

[Note: This script assumes you already have an understanding of functions in PowerShell]

Lets assume you want to select your favourite mail provider’s domain from the string below

$xCSVList = "gmail.com,hotmail.com,yahoo.com,mail.com,outlook.com"

Split the CSV string (xCSVList) into a Hash Table stored as xPickListValues

$xPickListValues = $xCSVList.split(",")

Convert the hash table to a multi-dimensional array, this is an array whose entry’s have two values in an sub-array of their own. Each Domain is stored with a number, except the first entry as it is 0 it is null.

foreach($entry in $xPickListValues){
#... foreach entry add to the array and increment the counter
$array += (,($i,$entry))

This can be represented in the table below

array [0] [1]
[0] gmail.com
[1] 1 hotmail.com
[2] 2 yahoo.com
[3] 3 mail.com
[4] 4 outlook.com

Next we output the actual pick list using write-host and tabs to format the menu.

foreach ($arrayentry in $array){
Write-Host $("`t`t`t"+$arrayentry[0]+".`t"+$arrayentry[1])

After we have presented the choices to the user we retrieve their chosen value

$xPickListSelection = Read-Host "`n`t`tEnter Option Number"

This can then be returned out of the function back to the calling code using the integer the user has entered retrieving the value from the Multi-Dimensional array..

return $array[$xPickListSelection][1]

This method allows us to create a re-usable pick list menu in PowerShell.

The entire script can be found HERE and includes two examples of required and optional pick list selections.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.