powershellhashtableenumerationkeyvaluepair

Convert hashtable back to string data in efficient way


I am trying to convert a hashtable back to key-value pair in an efficient way. Currently I am using this:

$kv = ""
$hash.GetEnumerator() | ForEach {
  $kv += "$($_.Name)=$($_.Value)"
}

Isn't there any way to directly convert hash table to key value pairs, or I mean string data. There is ConvertFrom-StringData to convert key value pairs to hash table. Isn't there any way to do the opposite, convert hash tables to key value pairs directly?

E.G(Key-Value pair)

a=1
b=2
c=3

Solution

  • I suggested this script cmdlet for this similar question:

    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:

    ConvertTo-StringData $hash 
    # or
    $hash | ConvertTo-StringData