Persisting a Hash Table
I was on a chat earlier today with one of our users. I’m not sure why, but he wanted to find a way to persist a Hash Table between PowerShell sessions. I was pretty sure the both Ed Wilson and Jeffery Hicks had addressed similar problems in the past, so I gave him links to their sites, but I figured there was probably a pretty easy way to do this. Here’s what I came up with as a basic premise:
PS C:\Users\jhofer> $myHash = @{“foo”=1;”ack”=2}
PS C:\Users\jhofer> $myHash
Name Value
—— ——-
foo 1
ack 2PS C:\Users\jhofer> $myHash | Export-Clixml c:\myhash.xml
PS C:\Users\jhofer> $newHash = Import-Clixml C:\myhash.xml
PS C:\Users\jhofer> $newHash
Name Value
—— ——-
ack 2
foo 1
PS C:\Users\jhofer> $newHash.Keys
ack
foo
So basically, it looks like he could add a line like $myHash = Import-Clixml C:\myhash.xml to his profile so that it would load his hash each time he starts up PowerShell. He could then add a PowerShell function to that would add or update values in his hash table and then overwrite the xml file. Here’s the final version of what I would add to the profile to accomplish this:
$global:persistentHash = @{}
$global:persistentHash = import-Clixml c:\Public\persistentHash.xml
function update-PersistentHash($key, $value)
{
if($global:persistentHash.Contains($key))
{
$global:persistentHash.Remove($key)
}
$global:persistentHash.Add($key,$value)
$global:persistentHash | export-Clixml c:\Public\persistentHash.xml -Force
}
5 months ago - link

