Simple Settings / Data Storage and Retrieval In the Registry |
![]() |
![]() |
PowerShell |
Written by Darwin Sanoy |
Thursday, February 5, 2015 9: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:
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\QQQGo check the registry key HKCU\SOftware\QQQ to see how it worked out! |