Using Hash Table as Conditional Code Repository

by Sep 18, 2015

It is routine for scripts to check whether a folder exists, and if it is missing, to create it:

#requires -Version 1

$path = 'c:\testfolder'
$exists = Test-Path -Path $path

if ($exists)
  $null = New-Item -Path $path -ItemType Directory
  Write-Warning -Message 'Folder created'
  Write-Warning -Message 'Folder already present'

Here is a highly unusual approach that does the same, just with a different concept:

#requires -Version 1

$Creator = @{
  $true = { Write-Warning 'Folder already present'}
  $false = {$null = New-Item -Path $Path -ItemType Directory
            Write-Warning 'Folder created'}

$Path = 'c:\testfolder2'
& $Creator[(Test-Path $Path)]

Actually, a hash table ($Creator) is used to store the two script blocks, and $true and $false is used for keys.

Now depending on whether the folder exists or not, the hash table returns the appropriate script block which is then executed using the & (Call) operator.

Hash tables mimick if clauses this way.

Twitter This Tip! ReTweet this Tip!