Simple Settings / Data Storage and Retrieval In the Registry Print E-mail
PowerShell
Written by Darwin Sanoy   
Thursday, February 5, 2015 8:16pm

Many times I've wanted a simple settings store for storing state data or settings for a script.  I thought there must be a built-in way to store and retrieve a hashtable in the registry - that would be leanest and most natural way to do it!  I was wrong... er, actually, now I am right - because like a good PowerSheller I went off and built it  :)

The design goals for this solution were:

  • Easily read arbitrary registry key value pairs from a registry key into a hash - all of them, whatever they are.
  • Easily write an arbitrary hashtable to a registry key (including autocreating the key if it does not exist)
  • Easily add new settings to the hashtable at any time.
  • And of course, when you rewrite those settings, any new ones you add will get set and read next time.
  • Easily write just one setting without having to write them all.

I'm hoping the code speaks for itself - because it's time to go hang with my family ;)

Function Set-HashToRegKey {
  Param (
  [hashtable]$HashTable,
  [string]$Path
  )
  If (!(Test-Path $Path)) 
    {
    New-Item $Path -force | out-null
    }
    $HashTable.keys | %{set-itemproperty $Path -name "$_" -value "$($HashTable.item($_))"}
}

Function Get-RegKeyToHash {
  Param (
  [string]$Path
  )
  $hashtable = @{}
  If (Test-Path $Path) 
    {
    Get-itemproperty $Path | %{$_.PSBase.Properties} | `
       ?{$_.name -inotlike "PS*"} | `
       %{$HashTable.set_item("$($_.name)","$($_.value)") }
    Return $hashtable
    }
  Else
    {
    Return $null
    }
}

#SAMPLE CODE:

$ConfigSettings = Get-RegKeyToHash Registry::HKCU\Software\QQQ

If (!$ConfigSettings)
  {
  #Set Defaults when the registry key did not exist or was empty
  $ConfigSettings = @{
    SettingsUpdateDate = (get-date)
    Setting1 = 0
    Setting2 = "none"
    Setting3 = "none"
    }
  }

#Change some config settings (whether we read them from the registry or used the defaults)
$configsettings.setting2 = "hi"
$configsettings.setting3 = "there"

#Create a setting that never existed before
$configsettings.brandnewsetting = "noob"

Set-HashToRegKey $configsettings Registry::HKCU\Software\QQQ
Go check the registry key HKCU\SOftware\QQQ to see how it worked out!