Powershell ConvertFrom-StringData inverse operation ConvertTo-StringData

Viewed 764

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.

1 Answers

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
Related