Use Hash Tables to Make Code Readable

Maybe you stumbled across code like this in the past:

$shell = New-Object -ComObject WScript.Shell
$value = $shell.Popup('Restart Computer?', 5, 'Important', 36)

"Choice: $value"

This chunk of code opens a dialog box and asks the user whether it is OK to restart the computer. The pop-up dialog has a built-in timeout so the code will never stall, even if running unattended.

However, since PowerShell is using an old COM method for this, it is widely controlled by cryptic ID numbers. How do you know that “36” represents a dialog with YesNo buttons and a question mark? How can you interpret the returned value?

Hash tables can be an easy way to wrap code numbers, and make code more readable. Have a look:

$timeoutSeconds = 5
$title = 'Important'
$message = 'Restart Computer?'

$buttons = @{
  OK               = 0
  OkCancel         = 1  
  AbortRetryIgnore = 2
  YesNoCancel      = 3
  YesNo            = 4
  RetryCancel      = 5

$icon = @{
  Stop        = 16
  Question    = 32
  Exclamation = 48
  Information = 64

$clickedButton = @{
  -1 = 'Timeout'
  1  = 'OK'
  2  = 'Cancel'
  3  = 'Abort'
  4  = 'Retry'
  5  = 'Ignore'
  6  = 'Yes'
  7  = 'No'

$shell = New-Object -ComObject WScript.Shell
$value = $shell.Popup($message, $timeoutSeconds, $title, $buttons.YesNo + $icon.Question)

"Raw result: $value"
"Cooked result: " + $clickedButton.$value

Switch ($clickedButton.$value)
  'Yes'    { 'restarting' }
  'No'     { 'aborted' }
  'Timeout'{ 'you did not make a choice' }

Thanks to the hash tables, instead of specifying “36”, the code uses $buttons.YesNo + $icon.Question, and once you ran the code (so the hash tables are defined), you even get IntelliSense for the available choices.

Likewise, the return code can easily be converted to a human readable format by using the raw return value as key to the hash table. This way, you can use a switch statement and assign script blocks to the buttons the user clicked, rather than having to know the individual button codes.

Twitter This Tip! ReTweet this Tip!

GD Star Rating