I want to keep hash table contents in a text file and then load it in new sessions. I was thinking of just storing them in a text file $env:TEMP\myhash.txt
as
xxx=123
yyy=234
I want to be able to update the contents of the hash in memory and the hash in the file (then those entries will load in the next session):
$myhash = @{}
function Add-HashEntry ($newkey, $newval) {
try { $myhash.Add( $newkey, $newval ) } catch { "already in hash" } # First add it to the hash in memory
$AddToFile = "$newkey=$newval" # Now save the key/value to file
$check = Select-String -Quiet -Pattern $AddToFile -Path $env:TEMP\myhash.txt
if (-not $check) { Add-Content -Path $env:TEMP\myhash.txt -Value $AddToFile } # "$mykey = $myval" >> $env:TEMP\myhash.txt
}
To load my hash from the file, I might use:
function Load-Hash {
foreach ($i in Get-Content $env:TEMP\myhash.txt) {
$key = ($i -split "=")[0] ; $val = ($i -split "=")[1]
$myhash.Add( $key, $val ) # Note: "Add (" not allowed, must use "Add("
}
}
This works, but my question is, are there more efficient ways to achieve this goal? i.e. better ways to store and retrieve the data from the file (maybe using json/xml or other better format) or ways that are more efficient to achieve the goal of storing and loading a hash table from a file than my hackish split by "=" and load the values method? Maybe even there is a way to load a file as a hash table directly etc?