3

I have found following code for reading hashtable from a text file with key=value pairs.

$value = Get-Content $Path | Out-String | ConvertFrom-StringData

I have not found the inverse operation though how to write the hashtable back to the text file in the same format. I use the following code

$values.GetEnumerator() | ForEach-Object { "{0}={1}" -f $_.Name,$_.Value } | Set-Content $Path

It works fine. I just wonder if there is some more straight forward solution.

marsze
  • 13,389
  • 5
  • 38
  • 53
Jirmed
  • 333
  • 1
  • 10

1 Answers1

4

Not that I know. This has been asked before.

Your solution looks fine. You could turn your code into a script cmdlet:

function ConvertTo-StringData {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
        [HashTable[]]$HashTable
    )
    process {
        foreach ($item in $HashTable) {
            foreach ($entry in $item.GetEnumerator()) {
                "{0}={1}" -f $entry.Key, $entry.Value
            }
        }
    }
}

Example:

$hashtable = Get-Content $path | ConvertFrom-StringData
$hashtable | ConvertTo-StringData | Set-Content $path
# or
ConvertTo-StringData $hashtable | Set-Content $path
marsze
  • 13,389
  • 5
  • 38
  • 53